diff --git a/README.MD b/README.MD index 4c0f2da..6f6ebfc 100644 --- a/README.MD +++ b/README.MD @@ -1,4 +1,7 @@ # ComfyUI Layer Style + +[中文说明点这里](./README_CN.MD) + A set of nodes for ComfyUI that can composite layer and mask to achieve Photoshop like functionality. It migrate some basic functions of PhotoShop to ComfyUI, aiming to centralize the workflow and reduce the frequency of software switching. @@ -6,17 +9,35 @@ It migrate some basic functions of PhotoShop to ComfyUI, aiming to centralize th ![image](image/title.png) *this workflow (title_example_workflow.json) is in the workflow directory.
-Nodes are divided into 5 groups according to their functions: LayerStyle, LayerColor, LayerMask, LayerUtility and LayerFilter. -* [LayerStyle](#LayerStyle) nodes provides layer styles that mimic Adobe Photoshop. -* [LayerColor](#LayerColor) node group provides color adjustment functionality. -* [LayerMask](#LayerMask) nodes provides mask assistance tools. -* [LayerUtility](#LayerUtility) nodes provides auxiliary nodes related to layer composit tools and workflows. -* [LayerFilter](#LayerFilter) nodes provides image effect filters. -[中文说明点这里](./README_CN.MD) + +## Example workflow +image Some JSON workflow files in the workflow directory, that is example for ComfyUI. + + +## How to install + +* Recommended use ComfyUI Manager for installation. + +* Or open the cmd window in the plugin directory of ComfyUI, like ```ComfyUI\custom_nodes```,type +``` +git clone https://github.com/chflame163/ComfyUI_LayerStyle.git +``` +* Or download the zip file and extracted, copy the resulting folder to ```ComfyUI\custom_ Nodes``` + +* Install dependency packages, open the cmd window in the ComfyUI_LayerStyle plugin directory like +```ComfyUI\custom_ Nodes\ComfyUI_LayerStyle``` and enter the following command: + +``` +..\..\..\python_embeded\python.exe -m pip install -r requirements.txt +``` + +* Restart ComfyUI. ## Update -**If the dependency package error after updating, please reinstall the relevant dependency packages. for details, please refer to [here](https://github.com/chflame163/ComfyUI_LayerStyle/issues/5). +**If the dependency package error after updating, please reinstall the relevant dependency packages. for details, please refer to [here](https://github.com/chflame163/ComfyUI_LayerStyle/issues/5).
+ +* Commit [LaMa](#LaMa) node, it can erase objects from the image based on the mask. this node is repackage of [IOPaint](https://www.iopaint.com). * Commit [ImageRemoveAlpha](#ImageRemoveAlpha) and [ImageCombineAlpha](#ImageCombineAlpha) nodes, alpha channel of the image can be removed or merged. * Commit [ImageScaleRestoreV2](#ImageScaleRestoreV2) and [ImageScaleByAspectRatioV2](#ImageScaleByAspectRatioV2) nodes, supports scaling images to specified long or short edge sizes. * Commit [PersonMaskUltra](#PersonMaskUltra) node, Generate masks for portrait's face, hair, body skin, clothing, or accessories. the model code for this node comes from [a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator). @@ -74,6 +95,19 @@ Add invalid mask input judgment and ignore it when invalid mask is input. * Commit [DropShadow](#DropShadow) node. +## Description +Nodes are divided into 5 groups according to their functions: LayerStyle, LayerColor, LayerMask, LayerUtility and LayerFilter. +* [LayerStyle](#LayerStyle) nodes provides layer styles that mimic Adobe Photoshop. +![image](image/menu_layer_style.png) +* [LayerColor](#LayerColor) node group provides color adjustment functionality. +![image](image/menu_layer_color.png) +* [LayerMask](#LayerMask) nodes provides mask assistance tools. +![image](image/menu_layer_mask.png) +* [LayerUtility](#LayerUtility) nodes provides auxiliary nodes related to layer composit tools and workflows. +![image](image/menu_layer_utility.png) +* [LayerFilter](#LayerFilter) nodes provides image effect filters. +![image](image/menu_layer_filter.png) + # LayerStyle ![image](image/layerstyle_title.png) ![image](image/layerstyle_nodes.png) @@ -604,6 +638,21 @@ Open the text editing software and find the line starting with "FONT_dir=", afte If the folder set in ini is invalid, the font folder that comes with the plugin will be enabled. +### LaMa +![image](image/lama_example.png) +Erase objects from the image based on the mask. this node is repackage of [IOPaint](https://www.iopaint.com), powered by state-of-the-art AI models. +It is have [LaMa](#https://github.com/advimman/lama), [LDM](https://github.com/CompVis/latent-diffusion), [ZITS](https://github.com/DQiaole/ZITS_inpainting),[MAT](https://github.com/fenglinglwb/MAT), [FcF](https://github.com/SHI-Labs/FcF-Inpainting), [Manga](https://github.com/msxie92/MangaInpainting) models and the OpenCV method to erase. Please refer to the original link for the introduction of each model. +Please download the model files from [lama models(Baidu Netdisk)](https://pan.baidu.com/s/1LllR9TJHP1G9uEwWT3Mvkg?pwd=tvzv) or [lama models(Google Drive)](https://drive.google.com/drive/folders/1Aq0a4sybb3SRxi7j1e1_ZbBRjaWDdP9e?usp=sharing) to ```ComfyUI/models/lama``` folder. + +Node optons: +![image](image/lama_node.png) +* lama_model: Choose a model or method. +* device: After correctly installing Torch and Nvidia CUDA drivers, using cuda will significantly improve running speed. +* invert_mask: Whether to reverse the mask. +* grow: Positive values expand outward, while negative values contract inward. +* blur: Blur the edge. + + ### ImageChannelSplit ![image](image/image_channel_split_example.png) Split the image channel into individual images. @@ -1012,22 +1061,5 @@ Node options: 5 The layer_image and layer_mask must be of the same size. - - - -## Example workflow -image Some JSON workflow files in the workflow directory, that is example for ComfyUI. - - -## How to install - -* Recommended use ComfyUI Manager for installation. - -* Or open the cmd window in the plugin directory of ComfyUI, like "ComfyUI\custom_nodes\",type```git clone https://github.com/chflame163/ComfyUI_LayerStyle.git``` -or download the zip file and extracted, copy the resulting folder to ComfyUI\custom_ Nodes\ - - Install dependency packages, open the cmd window in the ComfyUI_LayerStyle plugin directory like "ComfyUI\custom_ Nodes\ComfyUI_LayerStyle" and enter the following command: - - ```..\..\..\python_embeded\python.exe -m pip install -r requirements.txt``` - - Restart ComfyUI. \ No newline at end of file +# statement +LayerStyle nodes follows the MIT license, Some of its functional code comes from other open-source projects. If used for commercial purposes, please refer to the original project license to authorization agreement. diff --git a/README_CN.MD b/README_CN.MD index 30e66ec..bbc065c 100644 --- a/README_CN.MD +++ b/README_CN.MD @@ -1,67 +1,106 @@ -# ComfyUI Layer Style -һ×éΪComfyUIÉè¼ƵĽڵ㣬¿ÉÒԺϳÉͼ²ã´ﵽÀàËÆPhotoshopµĹ¦Äܡ£ÕâЩ½ڵ㽫PhotoShopµÄһ²¿·ֻù±¾¹¦ÄÜǨÒƵ½ComfyUI£¬ּÔڼ¯Öй¤×÷Á÷³̣¬¼õÉÙÈí¼þÇл»µÄƵÂʡ£ +# ComfyUI Layer Style +一组为ComfyUI设计的节点,可以合成图层达到类似Photoshop的功能。这些节点将PhotoShop的一部分基本功能迁移到ComfyUI,旨在集中工作流程,减少软件切换的频率。 ![image](image/title.png) -*´Ëͼ¹¤×÷Á÷(title_example_workflow.json) ÔÚ workflow Ŀ¼ÖÐ.
+*此图工作流(title_example_workflow.json) 在 workflow 目录中.
-½ڵ㰴Õչ¦ÄܷÖΪ5×飺LayerStyle, LayerColor, LayerMask, LayerUtilityºÍLayerFilter¡£ -* [LayerStyle](#LayerStyle)½ڵã×éÌṩ·ÂÕÕAdobe PhotoshopµÄͼ²ãÑùʽ¡£ -* [LayerColor](#LayerColor)½ڵã×éÌṩµ÷ÕûÑÕɫ¹¦Äܡ£ -* [LayerMask](#LayerMask)½ڵã×éÌṩMask¸¨Öú¹¤¾ߡ£ -* [LayerUtility](#LayerUtility)½ڵã×éÌṩͼ²ãºϳɹ¤¾ߺ͹¤×÷Á÷Ïà¹صĸ¨Öú½ڵ㡣 -* [LayerFilter](#LayerFilter)½ڵã×éÌṩͼÏñЧ¹ûÂ˾µ¡£ -## ¸üÐÂ˵Ã÷ -**Èç¹û±¾²å¼þ¸üкó³öÏÖÒÀÀµ°ü´íÎó£¬ÇëÖØÐ°²װÏà¹ØÒÀÀµ°ü¡£ÏêÇé¼û[ÕâÀï](https://github.com/chflame163/ComfyUI_LayerStyle/issues/5)¡£ -* Ìí¼Ó [ImageRemoveAlpha](#ImageRemoveAlpha) ºÍ [ImageCombineAlpha](#ImageCombineAlpha) ½ڵ㣬¿ÉÒƳý»òºϲ¢ͼƬµÄalphaͨµÀ¡£ -* Ìí¼Ó [ImageScaleRestoreV2](#ImageScaleRestoreV2) ºÍ [ImageScaleByAspectRatioV2](#ImageScaleByAspectRatioV2) ½ڵ㡣֧³ְ´ָ¶¨µij¤±߻ò¶̱߳ߴçËõ·ÅͼÏñ¡£ -* Ìí¼Ó [PersonMaskUltra](#PersonMaskUltra) ½ڵ㣬ΪÈËÎïÉú³ÉÁ³¡¢ͷ·¢¡¢ÉíÌåƤ·ô¡¢Ò·þ»òÅäÊεÄÕÚÕ֡£±¾½ڵãµÄģÐʹúÂëÀ´×Ô[a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator)¡£ -* Ìí¼Ó [LightLeak](#LightLeak) ½ڵ㣬Õâ¸öÂ˾µģÄ⽺Ƭ©¹âЧ¹û¡£ -* Ìí¼Ó [Film](#Film) ½ڵã, Õâ¸öÂ˾µģÄ⽺ƬµĿÅÁ£¡¢°µ±ߺͱßԵģºý£¬֧³ÖÊäÈëÉî¶ÈͼģÄâÐ齹£¬ÊÇ[digitaljohn/comfyui-propost](https://github.com/digitaljohn/comfyui-propost)µÄÖØÐ·âװ¡£ -* Ìí¼Ó [ImageAutoCrop](#ImageAutoCrop) ½ڵã, Õâ¸ö½ڵãÊÇΪÉú³ÉѵÁ·ģÐ͵ÄͼƬËزĶøÉè¼Ƶġ£ -* Ìí¼Ó [ImageScaleByAspectRatio](#ImageScaleByAspectRatio) ½ڵ㣬 ¿ɰ´»­·ù±ÈÀýËõ·ÅͼÏñ¡£ -* ¸ÄÕý [LUT Apply](#LUT) ½ڵãäÖȾ³öÏÖɫ½׵Äbug, ²¢Ôö¼Ólogɫ²ʿռä֧³֡£*logɫ²ʿռäͼƬÇë¼ÓÔØרÃŵÄlog lut¡£ -* Ìí¼Ó [CreateGradientMask](#CreateGradientMask) ½ڵ㡣Ìí¼Ó [LayerImageTransform](#LayerImageTransform) ºÍ [LayerMaskTransform](#LayerMaskTransform) ½ڵ㡣 -* Ìí¼Ó [MaskEdgeUltraDetail](#MaskEdgeUltraDetail) ½ڵ㣬¸ø´ֲڵÄÕÚÕֽøÐд¦Àí»ñµó¬¾«ϸµıßԵ¡£Ìí¼Ó [Exposure](#Exposure) ½ڵ㣬µ÷ÕûͼÏñÆع⡣ -* Ìí¼Ó [Sharp & Soft](#Sharp) ½ڵ㣬¿ÉÌáÉý»òĨƽͼÏñϸ½ڡ£ÐÂÔö[MaskByDifferent](#MaskByDifferent)½ڵ㣬±ȽÏÁ½ÕÅͼƬ²¢Êä³öMask¡£ÐÂÔö[SegmentAnythingUltra](#SegmentAnythingUltra)½ڵ㣬ÌáÉýÕÚÕֱßԵÖÊÁ¿¡£*Èç¹ûûÓа²װSegmentAnything, ÐèҪÊֶ¯ÏÂÔØģÐ͡£ -* ËùÓнڵãÒÑȫÃæ֧³ÖÅúÁ¿ͼƬ£¬Ϊ´´×÷ÊÓƵÌṩ·½±㡣( CropByMask ½ڵã½ö֧³ÖÏàͬ³ߴçµÄÇгý, Èç¹ûÊäÈëÅúÁ¿mask_for_crop£¬½«ʹÓõÚһÕŵÄÊý¾ݡ£) -* Ìí¼Ó [RemBgUltra](#RemBgUltra) ºÍ [PixelSpread](#PixelSpread) ½ڵ㣬ÏÔÖøÌáÉýÁËÕÚÕÖÖÊÁ¿¡£*RemBgUltraÐèÊֶ¯ÏÂÔØģÐ͡£ -* Ìí¼Ó [TextImage](#TextImage) ½ڵ㣬Éú³ÉÎÄ×ÖͼÏñºÍÕÚÕ֡£ -* ͼÏñ֮¼äµÄ[»ìºÏģʽ](#»ìºÏģʽ)Ôö¼ÓÐÂÀàÐͣ¬ÏÖÔÚ֧³ֶà´ï19ÖֻìºÏģʽ¡£ÐÂÔöcolor_burnÑÕɫ¼ÓÉî, color_dodgeÑÕɫ¼õµ­, linear_burnÏßÐԼÓÉî, linear_dodgeÏßÐԼõµ­, overlayµþ¼Ó, soft_lightÈá¹â, hard_lightǿ¹â, vivid_lightÁÁ¹â, pin_lightµã¹â, linear_lightÏßÐԹâ, hard_mixʵɫ»ìºϡ£ÐÂÔöµĻìºÏģʽÊÊÓÃÓÚËùÓÐ֧³ֻìºÏģʽµĽڵ㡣 -* Ìí¼Ó [ColorMap](#ColorMap) Â˾µ½ڵ㣬ÓÃÓÚÖÆ×÷α²ÊɫÈÈÁ¦ͼЧ¹û¡£ -* Ìí¼Ó [WaterColor](#WaterColor) ºÍ [SkinBeauty](#SkinBeauty) ½ڵ㡣ÕâÊÇÁ½¸öͼÏñÂ˾µ£¬Éú³Éˮ²ʻ­ºÍĥƤЧ¹û¡£ -* Ìí¼Ó [ImageShift](#ImageShift) ½ڵ㣬ʹͼƬ²úÉúλÒƣ¬¿ÉÊä³öλÒƽӷìÕÚÕ֣¬·½±ãÖÆ×÷Á¬ÐøÌùͼ¡£ -* Ìí¼Ó [ImageMaskScaleAs](#ImageMaskScaleAs) ½ڵ㣬¿ɸù¾ݲο¼ͼƬµ÷ÕûͼÏñ»òÕÚÕִóС¡£ -* Ìí¼Ó [ImageScaleRestore](#ImageScaleRestore) ½ڵ㣬ÓÃÓÚÅäºÏCropByMask½øÐоֲ¿·ŴóÐ޸´¹¤×÷¡£ -* Ìí¼Ó [CropByMask](#CropByMask) ºÍ [RestoreCropBox](#RestoreCropBox)½ڵ㡣´˶þÕßÅäºϿɽ«ͼƬ¾ֲ¿²ÃÇÐÖػæȻºó»¹ԭ¡£ -* Ìí¼Ó [ColorAdapter](#ColorAdapter) ½ڵ㣬¿É×Զ¯µ÷ÕûͼƬɫµ÷¡£ -* Ìí¼Ó [MaskStroke](#MaskStroke) ½ڵ㣬¿ɲúÉúmaskÃè±ߡ£ -* Ìí¼Ó [LayerColor](#LayerColor)½ڵã×飬ÓÃÓڵ÷ÕûͼÏñÑÕɫ¡£°üÀ¨[LUT Apply](#LUT)£¬[Gamma](#Gamma), [Brightness & Contrast](#Brightness), [RGB](#RGB), [YUV](#YUV), [LAB](#LAB)ºÍ[HSV](#HSV)¡£ -* Ìí¼Ó [ImageChannelSplit](#ImageChannelSplit)ºÍ[ImageChannelMerge](#ImageChannelMerge)½ڵ㡣 -* Ìí¼Ó [MaskMotionBlur](#MaskMotionBlur)½ڵ㡣 -* Ìí¼Ó [SoftLight](#SoftLight)½ڵ㡣 -* Ìí¼Ó [ChannelShake](#ChannelShake)½ڵ㣬ÕâÊÇһ¸öÂ˾µ£¬ÄܲúÉúÀàËƶ¶ÒôlogoµÄͨµÀ´íλЧ¹û¡£ -* Ìí¼Ó [MaskGradient](#MaskGradient)½ڵ㣬¿Éʹmask²úÉú½¥±䡣 -* Ìí¼Ó [GetColorTone](#GetColorTone)½ڵ㣬¿ÉÒԻñȡͼƬµÄÖ÷ɫ»òƽ¾ùɫ¡£Ìí¼Ó[MaskGrow](#MaskGrow)ºÍ[MaskEdgeShrink](#MaskEdgeShrink)½ڵ㡣 +## 工作流用示例 +在workflow目录下有json格式的工作流示例文件。 -* Ìí¼Ó [MaskBoxDetect](#MaskBoxDetect)½ڵ㣬¿ÉÒÔͨ¹ýmask×Զ¯̽²âλÖò¢Êä³öµ½ºϳɽڵ㡣Ìí¼Ó[XY to Percent](#Percent)½ڵ㣬½«¾ø¶Ô×ø±êת»»Ϊpercent×ø±ꡣÌí¼Ó[GaussianBlur](#GaussianBlur)½ڵ㡣Ìí¼Ó[GetImageSize](#GetImageSize)½ڵ㡣 -* Ìí¼Ó [ExtendCanvas](#ExtendCanvas)½ڵ㡣 -* Ìí¼Ó [ImageBlendAdvance](#ImageBlendAdvance)½ڵ㡣Õâ¸ö½ڵãÔÊÐíºϳɳߴ粻ͬµı³¾°ͼºÍͼ²㣬ÌṩÁ˸ü¼Ó×ÔÓɵĺϳÉÌåÑ顣 - Ìí¼Ó [PrintInfo](#PrintInfo)½ڵã×÷Ϊ¹¤×÷Á÷µ÷ÊԸ¨Öú¹¤¾ߡ£ -* Ìí¼Ó [ColorImage](#ColorImage)ºÍ[GradientImage](#GradientImage)½ڵ㣬ÓÃÓÚÉú³ɴ¿ɫºͽ¥±äɫͼÏñ¡£ -* Ìí¼Ó [GradientOverlay](#GradientOverlay),[ColorOverlay](#ColorOverlay)½ڵ㡣Ôö¼ÓÎÞЧmaskÊäÈëÅжϣ¬µ±ÊäÈëÎÞЧmaskʱ½«ÆäºöÂԡ£ -* Ìí¼Ó [InnerGlow](#InnerGlow), [InnerShadow](#InnerShadow), [MotionBlur](#MotionBlur)½ڵ㡣 -* ËùÓÐÒÑÍê³ɵĽڵãÖØÐÂÃüÃû£¬½ڵã·ÖΪ4×飺LayerStyle, LayerMask, LayerUtility, LayerFilter¡£ - ÒòΪÖØÐÂÃüÃû£¬°üº¬¾ɰæ½ڵãµĹ¤×÷Á÷ÐèÊֶ¯Ì滻аæ½ڵ㡣 -* [OuterGlow](#OuterGlow)½ڵãÐ޸ģ¬Ôö¼ÓÁÁ¶ȡ¢µƹâÑÕɫ¡¢»ԹâÑÕɫѡÏ -* Ìí¼Ó [MaskInvert](#MaskInvert)½ڵ㡣 -* Ìí¼Ó [Stroke](#Stroke)½ڵ㡣 -* Ìí¼Ó [MaskPreview](#MaskPreview)½ڵ㡣 -* Ìí¼Ó [ImageOpacity](#ImageOpacity)½ڵ㡣 -* layer_maskÐ޸ÄΪ·DZØѡ, ĬÈÏʹÓÃlayer_imageµÄalphaͨµÀ£¬ÔÊÐíͨ¹ýÊäÈëmask¸ıä֮£¬µ«Êdzߴç±ØÐëһÖ¡£ -* Ìí¼Ó [ImageBlend](#ImageBlend)½ڵ㡣 -* Ìí¼Ó [OuterGlow](#OuterGlow)½ڵ㡣 -* Ê׸ö½ڵã [DropShadow](#DropShadow)Ìύ¡£ + +## 安装方法 + +* 推荐使用 ComfyUI Manager 安装。 +* 或者在CompyUI插件目录(例如“CompyUI\custom_nodes\”)中打开cmd窗口,键入 +``` +git clone https://github.com/chflame163/ComfyUI_LayerStyle.git +``` + +* 或者下载解压zip文件,将得到的文件夹复制到 ```ComfyUI\custom_nodes\```。 + +* 安装依赖包,在资源管理器```ComfyUI\custom_nodes\ComfyUI_LayerStyle``` 插件目录位置打开cmd窗口,输入以下命令: +``` +..\..\..\python_embeded\python.exe -m pip install -r requirements.txt +``` + + + 重新打开ComfyUI。 + +## 如何找到本节点组 +* 在ComfyUI画布点击右键 - Add Node, 找到 "😺dzNodes"。 +![image](image/node-menu.png) + +* 或者在ComfyUI画布双击, 在搜索框输入"layer"。 +![image](image/node-search.png) + + +## 更新说明 +**如果本插件更新后出现依赖包错误,请重新安装相关依赖包。详情见[这里](https://github.com/chflame163/ComfyUI_LayerStyle/issues/5)。
+ +* 添加 [Lama](#Lama) 节点,根据图像遮罩擦除物体。本节点是对[IOPaint](https://www.iopaint.com)的封装。 +* 添加 [ImageRemoveAlpha](#ImageRemoveAlpha) 和 [ImageCombineAlpha](#ImageCombineAlpha) 节点,可移除或合并图片的alpha通道。 +* 添加 [ImageScaleRestoreV2](#ImageScaleRestoreV2) 和 [ImageScaleByAspectRatioV2](#ImageScaleByAspectRatioV2) 节点。支持按指定的长边或短边尺寸缩放图像。 +* 添加 [PersonMaskUltra](#PersonMaskUltra) 节点,为人物生成脸、头发、身体皮肤、衣服或配饰的遮罩。本节点的模型代码来自[a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator)。 +* 添加 [LightLeak](#LightLeak) 节点,这个滤镜模拟胶片漏光效果。 +* 添加 [Film](#Film) 节点, 这个滤镜模拟胶片的颗粒、暗边和边缘模糊,支持输入深度图模拟虚焦,是[digitaljohn/comfyui-propost](https://github.com/digitaljohn/comfyui-propost)的重新封装。 +* 添加 [ImageAutoCrop](#ImageAutoCrop) 节点, 这个节点是为生成训练模型的图片素材而设计的。 +* 添加 [ImageScaleByAspectRatio](#ImageScaleByAspectRatio) 节点, 可按画幅比例缩放图像。 +* 改正 [LUT Apply](#LUT) 节点渲染出现色阶的bug, 并增加log色彩空间支持。*log色彩空间图片请加载专门的log lut。 +* 添加 [CreateGradientMask](#CreateGradientMask) 节点。添加 [LayerImageTransform](#LayerImageTransform) 和 [LayerMaskTransform](#LayerMaskTransform) 节点。 +* 添加 [MaskEdgeUltraDetail](#MaskEdgeUltraDetail) 节点,给粗糙的遮罩进行处理获得超精细的边缘。添加 [Exposure](#Exposure) 节点,调整图像曝光。 +* 添加 [Sharp & Soft](#Sharp) 节点,可提升或抹平图像细节。新增[MaskByDifferent](#MaskByDifferent)节点,比较两张图片并输出Mask。新增[SegmentAnythingUltra](#SegmentAnythingUltra)节点,提升遮罩边缘质量。*如果没有安装SegmentAnything, 需要手动下载模型。 +* 所有节点已全面支持批量图片,为创作视频提供方便。( CropByMask 节点仅支持相同尺寸的切除, 如果输入批量mask_for_crop,将使用第一张的数据。) +* 添加 [RemBgUltra](#RemBgUltra) 和 [PixelSpread](#PixelSpread) 节点,显著提升了遮罩质量。*RemBgUltra需手动下载模型。 +* 添加 [TextImage](#TextImage) 节点,生成文字图像和遮罩。 +* 图像之间的[混合模式](#混合模式)增加新类型,现在支持多达19种混合模式。新增color_burn颜色加深, color_dodge颜色减淡, linear_burn线性加深, linear_dodge线性减淡, overlay叠加, soft_light柔光, hard_light强光, vivid_light亮光, pin_light点光, linear_light线性光, hard_mix实色混合。新增的混合模式适用于所有支持混合模式的节点。 +* 添加 [ColorMap](#ColorMap) 滤镜节点,用于制作伪彩色热力图效果。 +* 添加 [WaterColor](#WaterColor) 和 [SkinBeauty](#SkinBeauty) 节点。这是两个图像滤镜,生成水彩画和磨皮效果。 +* 添加 [ImageShift](#ImageShift) 节点,使图片产生位移,可输出位移接缝遮罩,方便制作连续贴图。 +* 添加 [ImageMaskScaleAs](#ImageMaskScaleAs) 节点,可根据参考图片调整图像或遮罩大小。 +* 添加 [ImageScaleRestore](#ImageScaleRestore) 节点,用于配合CropByMask进行局部放大修复工作。 +* 添加 [CropByMask](#CropByMask) 和 [RestoreCropBox](#RestoreCropBox)节点。此二者配合可将图片局部裁切重绘然后还原。 +* 添加 [ColorAdapter](#ColorAdapter) 节点,可自动调整图片色调。 +* 添加 [MaskStroke](#MaskStroke) 节点,可产生mask描边。 +* 添加 [LayerColor](#LayerColor)节点组,用于调整图像颜色。包括[LUT Apply](#LUT),[Gamma](#Gamma), [Brightness & Contrast](#Brightness), [RGB](#RGB), [YUV](#YUV), [LAB](#LAB)和[HSV](#HSV)。 +* 添加 [ImageChannelSplit](#ImageChannelSplit)和[ImageChannelMerge](#ImageChannelMerge)节点。 +* 添加 [MaskMotionBlur](#MaskMotionBlur)节点。 +* 添加 [SoftLight](#SoftLight)节点。 +* 添加 [ChannelShake](#ChannelShake)节点,这是一个滤镜,能产生类似抖音logo的通道错位效果。 +* 添加 [MaskGradient](#MaskGradient)节点,可使mask产生渐变。 +* 添加 [GetColorTone](#GetColorTone)节点,可以获取图片的主色或平均色。添加[MaskGrow](#MaskGrow)和[MaskEdgeShrink](#MaskEdgeShrink)节点。 + +* 添加 [MaskBoxDetect](#MaskBoxDetect)节点,可以通过mask自动探测位置并输出到合成节点。添加[XY to Percent](#Percent)节点,将绝对坐标转换为percent坐标。添加[GaussianBlur](#GaussianBlur)节点。添加[GetImageSize](#GetImageSize)节点。 +* 添加 [ExtendCanvas](#ExtendCanvas)节点。 +* 添加 [ImageBlendAdvance](#ImageBlendAdvance)节点。这个节点允许合成尺寸不同的背景图和图层,提供了更加自由的合成体验。 + 添加 [PrintInfo](#PrintInfo)节点作为工作流调试辅助工具。 +* 添加 [ColorImage](#ColorImage)和[GradientImage](#GradientImage)节点,用于生成纯色和渐变色图像。 +* 添加 [GradientOverlay](#GradientOverlay),[ColorOverlay](#ColorOverlay)节点。增加无效mask输入判断,当输入无效mask时将其忽略。 +* 添加 [InnerGlow](#InnerGlow), [InnerShadow](#InnerShadow), [MotionBlur](#MotionBlur)节点。 +* 所有已完成的节点重新命名,节点分为4组:LayerStyle, LayerMask, LayerUtility, LayerFilter。 + 因为重新命名,包含旧版节点的工作流需手动替换新版节点。 +* [OuterGlow](#OuterGlow)节点修改,增加亮度、灯光颜色、辉光颜色选项。 +* 添加 [MaskInvert](#MaskInvert)节点。 +* 添加 [Stroke](#Stroke)节点。 +* 添加 [MaskPreview](#MaskPreview)节点。 +* 添加 [ImageOpacity](#ImageOpacity)节点。 +* layer_mask修改为非必选, 默认使用layer_image的alpha通道,允许通过输入mask改变之,但是尺寸必须一致。 +* 添加 [ImageBlend](#ImageBlend)节点。 +* 添加 [OuterGlow](#OuterGlow)节点。 +* 首个节点 [DropShadow](#DropShadow)提交。 + +## 节点说明 +节点按照功能分为5组:LayerStyle, LayerColor, LayerMask, LayerUtility和LayerFilter。 +* [LayerStyle](#LayerStyle)节点组提供仿照Adobe Photoshop的图层样式。 +![image](image/menu_layer_style.png) +* [LayerColor](#LayerColor)节点组提供调整颜色功能。 +![image](image/menu_layer_color.png) +* [LayerMask](#LayerMask)节点组提供Mask辅助工具。 +![image](image/menu_layer_mask.png) +* [LayerUtility](#LayerUtility)节点组提供图层合成工具和工作流相关的辅助节点。 +![image](image/menu_layer_utility.png) +* [LayerFilter](#LayerFilter)节点组提供图像效果滤镜。 +![image](image/menu_layer_filter.png) # LayerStyle @@ -70,602 +109,616 @@ ### DropShadow -Éú³ÉÒõӰ¡£ +生成阴影。 ![image](image/drop_shadow_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/drop_shadow_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1,2: ²ãͼÏñµÄÕÚÕ֣¬ÒõӰ°´´ËÉú³ɡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ÒõӰµĻìºÏģʽ¡£ -* opacity: ÒõӰµIJ»͸Ã÷¶ȡ£ -* distance_x: ÒõӰµÄˮƽ·½ÏòƫÒÆÁ¿¡£ -* distance_y: ÒõӰµĴ¹ֱ·½ÏòƫÒÆÁ¿¡£ -* grow: ÒõӰÀ©Õŷù¶ȡ£ -* blur:ÒõӰģºý³̶ȡ£ -* shadow_color4: ÒõӰÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩,阴影按此生成。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 阴影的混合模式。 +* opacity: 阴影的不透明度。 +* distance_x: 阴影的水平方向偏移量。 +* distance_y: 阴影的垂直方向偏移量。 +* grow: 阴影扩张幅度。 +* blur:阴影模糊程度。 +* shadow_color4: 阴影颜色。 +* [节点注解](#节点注解) ### OuterGlow -Éú³ÉÍⷢ¹⡣ +生成外发光。 ![image](image/outer_glow_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/outer_glow_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1,2: ²ãͼÏñµÄÕÚÕ֣¬Íⷢ¹ⰴ´ËÉú³ɡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ·¢¹âµĻìºÏģʽ¡£ -* opacity: ·¢¹âµIJ»͸Ã÷¶ȡ£ -* brightness: ·¢¹âÁÁ¶ȡ£ -* glow_range: ·¢¹ⷶΧ¡£ -* blur:·¢¹âģºý³̶ȡ£ -* light_color4: ·¢¹âÖÐÐÄÑÕɫ¡£ -* glow_colo4: »ԹâÍâΧÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩,外发光按此生成。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 发光的混合模式。 +* opacity: 发光的不透明度。 +* brightness: 发光亮度。 +* glow_range: 发光范围。 +* blur:发光模糊程度。 +* light_color4: 发光中心颜色。 +* glow_colo4: 辉光外围颜色。 +* [节点注解](#节点注解) ### InnerShadow -Éú³ÉÄÚÒõӰ¡£ +生成内阴影。 ![image](image/inner_shadow_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/inner_shadow_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1,2: ²ãͼÏñµÄÕÚÕ֣¬ÒõӰ°´´ËÉú³ɡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ÒõӰµĻìºÏģʽ¡£ -* opacity: ÒõӰµIJ»͸Ã÷¶ȡ£ -* distance_x: ÒõӰµÄˮƽ·½ÏòƫÒÆÁ¿¡£ -* distance_y: ÒõӰµĴ¹ֱ·½ÏòƫÒÆÁ¿¡£ -* grow: ÒõӰÀ©Õŷù¶ȡ£ -* blur:ÒõӰģºý³̶ȡ£ -* shadow_color4: ÒõӰÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩,阴影按此生成。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 阴影的混合模式。 +* opacity: 阴影的不透明度。 +* distance_x: 阴影的水平方向偏移量。 +* distance_y: 阴影的垂直方向偏移量。 +* grow: 阴影扩张幅度。 +* blur:阴影模糊程度。 +* shadow_color4: 阴影颜色。 +* [节点注解](#节点注解) ### InnerGlow -Éú³ÉÄڷ¢¹⡣ +生成内发光。 ![image](image/inner_glow_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/inner_glow_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1,2: ²ãͼÏñµÄÕÚÕ֣¬·¢¹ⰴ´ËÉú³ɡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ·¢¹âµĻìºÏģʽ¡£ -* opacity: ·¢¹âµIJ»͸Ã÷¶ȡ£ -* brightness: ·¢¹âÁÁ¶ȡ£ -* glow_range: ·¢¹ⷶΧ¡£ -* blur:·¢¹âģºý³̶ȡ£ -* light_color4: ·¢¹âÖÐÐÄÑÕɫ¡£ -* glow_colo4: »ԹâÍâΧÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩,发光按此生成。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 发光的混合模式。 +* opacity: 发光的不透明度。 +* brightness: 发光亮度。 +* glow_range: 发光范围。 +* blur:发光模糊程度。 +* light_color4: 发光中心颜色。 +* glow_colo4: 辉光外围颜色。 +* [节点注解](#节点注解) ### Stroke -Éú³ÉÃè±ߡ£ +生成描边。 ![image](image/stroke_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/stroke_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1£¬2: ²ãͼÏñµÄÕÚÕ֣¬Ãè±߰´´ËÉú³ɡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: Ãè±ߵĻìºÏģʽ¡£ -* opacity: ²»͸Ã÷¶ȡ£ -* stroke_grow: Ãè±ßÀ©ÕÅ/ÊÕËõ·ù¶ȣ¬ÕýֵÊÇÀ©Õţ¬¸ºֵÊÇÊÕËõ¡£ -* stroke_width: Ãè±߿í¶ȡ£ -* blur: Ãè±ßģºý¡£ -* stroke_color4: Ãè±ßÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩,描边按此生成。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 描边的混合模式。 +* opacity: 不透明度。 +* stroke_grow: 描边扩张/收缩幅度,正值是扩张,负值是收缩。 +* stroke_width: 描边宽度。 +* blur: 描边模糊。 +* stroke_color4: 描边颜色。 +* [节点注解](#节点注解) ### GradientOverlay -½¥±串¸Ç +渐变覆盖 ![image](image/gradient_overlay_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/gradient_overlay_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1£¬2: ²ãͼÏñµÄÕÚÕ֡£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: Ãè±ߵĻìºÏģʽ¡£ -* opacity: ²»͸Ã÷¶ȡ£ -* start_color: ½¥±俪ʼ¶˵ÄÑÕɫ¡£ -* start_alpha: ½¥±俪ʼ¶˵Ä͸Ã÷¶ȡ£ -* end_color: ½¥±ä½áÊø¶˵ÄÑÕɫ¡£ -* end_alpha: ½¥±ä½áÊø¶˵Ä͸Ã÷¶ȡ£ -* angle: ½¥±äÐýת½Ƕȡ£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 描边的混合模式。 +* opacity: 不透明度。 +* start_color: 渐变开始端的颜色。 +* start_alpha: 渐变开始端的透明度。 +* end_color: 渐变结束端的颜色。 +* end_alpha: 渐变结束端的透明度。 +* angle: 渐变旋转角度。 +* [节点注解](#节点注解) ### ColorOverlay -ÑÕɫ¸²¸Ç +颜色覆盖 ![image](image/color_overlay_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/color_overlay_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1£¬2: ²ãͼÏñµÄÕÚÕ֡£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: Ãè±ߵĻìºÏģʽ¡£ -* opacity: ²»͸Ã÷¶ȡ£ -* color: ¸²¸ǵÄÑÕɫ¡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 描边的混合模式。 +* opacity: 不透明度。 +* color: 覆盖的颜色。 +* [节点注解](#节点注解) # LayerColor ![image](image/layercolor_title.png) ![image](image/layercolor_nodes.png) ### LUT Apply -½«LUTӦÓõ½ͼÏ񡣽ö֧³Ö.cube¸ñʽµÄLUTÎļþ¡£ +将LUT应用到图像。仅支持.cube格式的LUT文件。 ![image](image/lut_apply_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/lut_apply_node.png) -* LUT*: ÕâÀïÁгöÁËLUTÎļþ¼ÐÖпÉÓõÄ.cubeÎļþÁбí£¬ѡÖеÄLUTÎļþ½«±»ӦÓõ½ͼÏñ¡£ -* color_space: ÆÕͨͼƬÇëѡÔñlinear, logɫ²ʿռäµÄͼƬÇëѡÔñlog¡£ +* LUT*: 这里列出了LUT文件夹中可用的.cube文件列表,选中的LUT文件将被应用到图像。 +* color_space: 普通图片请选择linear, log色彩空间的图片请选择log。 -*LUTÎļþ¼ÐÔÚresource_dir.iniÖж¨Ò壬Õâ¸öÎļþλÓڲå¼þ¸ùĿ¼Ï¡£ÓÃÎı¾±༭Èí¼þ´򿪣¬Õҵ½¡°LUT_dir=¡±¿ªͷµÄÕâһÐУ¬±༭¡°=¡±֮ºóΪ×Զ¨ÒåÎļþ¼Ð·¾¶Ãû¡£Õâ¸öÎļþ¼ÐÀïÃæËùÓеÄ.cubeÎļþ½«ÔÚComfyUI³õʼ»¯ʱ±»Êռ¯²¢ÏÔʾÔڽڵãµÄÁбíÖС£Èç¹ûiniÖÐÉ趨µÄÎļþ¼ÐÎÞЧ£¬½«ÆôÓòå¼þ×ԴøµÄLUTÎļþ¼С£ +*LUT文件夹在resource_dir.ini中定义,这个文件位于插件根目录下。用文本编辑软件打开,找到“LUT_dir=”开头的这一行,编辑“=”之后为自定义文件夹路径名。这个文件夹里面所有的.cube文件将在ComfyUI初始化时被收集并显示在节点的列表中。如果ini中设定的文件夹无效,将启用插件自带的LUT文件夹。 ### ColorAdapter -×Զ¯µ÷ÕûͼƬɫµ÷£¬ʹ֮Óë²ο¼ͼƬÏàËơ£ +自动调整图片色调,使之与参考图片相似。 ![image](image/color_adapter_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/color_adapter_node.png) -* opacity: ͼÏñµ÷Õûɫµ÷֮ºóµIJ»͸Ã÷¶ȡ£ +* opacity: 图像调整色调之后的不透明度。 ### Exposure -¸ıäͼÏñµÄÆع⡣ +改变图像的曝光。 ![image](image/exposure_example.png) -½ڵãѡÏî˵Ã÷: -* exposure: Æعâֵ¡£¸ü¸ߵÄÊýֵ±íʾ¸üÁÁµÄÆع⡣ +节点选项说明: +* exposure: 曝光值。更高的数值表示更亮的曝光。 ### Gamma -¸ıäͼÏñµÄGammaֵ¡£ +改变图像的Gamma值。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/gamma_node.png) -* gamma: ͼÏñµÄGammaֵ¡£ +* gamma: 图像的Gamma值。 ### Brightness & Contrast -¸ıäͼÏñµÄÁÁ¶ȡ¢¶ԱȶȺͱ¥ºͶȡ£ +改变图像的亮度、对比度和饱和度。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/brightness_&_contrast_node.png) -* brightness: ͼÏñµÄÁÁ¶ȡ£ -* contrast: ͼÏñµĶԱȶȡ£ -* saturation: ͼÏñµÄɫ²ʱ¥ºͶȡ£ +* brightness: 图像的亮度。 +* contrast: 图像的对比度。 +* saturation: 图像的色彩饱和度。 ### RGB -¶ÔͼÏñµÄRGB¸÷ͨµÀ½øÐе÷Õû¡£ +对图像的RGB各通道进行调整。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/RGB_node.png) -* R: ͼÏñµÄRͨµÀ¡£ -* G: ͼÏñµÄGͨµÀ¡£ -* B: ͼÏñµÄBͨµÀ¡£ +* R: 图像的R通道。 +* G: 图像的G通道。 +* B: 图像的B通道。 ### YUV -¶ÔͼÏñµÄYUV¸÷ͨµÀ½øÐе÷Õû¡£ +对图像的YUV各通道进行调整。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/YUV_node.png) -* Y: ͼÏñµÄYͨµÀ¡£ -* U: ͼÏñµÄUͨµÀ¡£ -* V: ͼÏñµÄVͨµÀ¡£ +* Y: 图像的Y通道。 +* U: 图像的U通道。 +* V: 图像的V通道。 ### LAB -¶ÔͼÏñµÄLAB¸÷ͨµÀ½øÐе÷Õû¡£ +对图像的LAB各通道进行调整。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/LAB_node.png) -* L: ͼÏñµÄLͨµÀ¡£ -* A: ͼÏñµÄAͨµÀ¡£ -* B: ͼÏñµÄBͨµÀ¡£ +* L: 图像的L通道。 +* A: 图像的A通道。 +* B: 图像的B通道。 ### HSV -¶ÔͼÏñµÄHSV¸÷ͨµÀ½øÐе÷Õû¡£ +对图像的HSV各通道进行调整。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/HSV_node.png) -* H: ͼÏñµÄHͨµÀ¡£ -* S: ͼÏñµÄSͨµÀ¡£ -* V: ͼÏñµÄVͨµÀ¡£ +* H: 图像的H通道。 +* S: 图像的S通道。 +* V: 图像的V通道。 # LayerUtility ![image](image/layerutility_nodes.png) ### ImageBlendAdvance -ÓÃÓںϳÉͼ²㣬ÔÊÐíÔڱ³¾°ͼƬÉϺϳÉÓë֮²»ͬ³ߴçµÄͼ²ãͼƬ£¬²¢ÇÒÉèÖÃλÖúͱ任¡£Ìṩ¶àÖֻìºÏģʽ¹©ѡÔ񣬿ÉÉèÖÃ͸Ã÷¶ȡ£ +用于合成图层,允许在背景图片上合成与之不同尺寸的图层图片,并且设置位置和变换。提供多种混合模式供选择,可设置透明度。 -½ڵãÌṩÁËͼ²ã±任·½·¨ºͿ¹¾â³ÝѡÏÓÐÖúÓÚÌá¸ߺϳɻ­Öʡ£ +节点提供了图层变换方法和抗锯齿选项。有助于提高合成画质。 -½ڵãÌṩÁËmaskÊä³ö¿ÉÓÃÓںóÐø¹¤×÷Á÷¡£ +节点提供了mask输出可用于后续工作流。 ![image](image/image_blend_advance_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_blend_advance_node.png) -* background_image: ±³¾°ͼÏñ¡£ -* layer_image5: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask2,5: ²ãͼÏñµÄÕÚÕ֡£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ͼ²ã»ìºÏģʽ¡£ -* opacity: ²»͸Ã÷¶ȡ£ -* x_percent: ͼ²ãÔڱ³¾°ͼÉϵÄˮƽλÖã¬Óðٷֱȱíʾ£¬×î×ó²àÊÇ0£¬×îÓҲàÊÇ100£¬¿ÉÒÔÊÇСÓÚ0»òÕ߳¬¹ý100£¬ÄDZíʾͼ²ãÓв¿·ÖÄÚÈÝÔڻ­Ãæ֮Í⡣ -* y_percent: ͼ²ãÔڱ³¾°ͼÉϵĴ¹ֱλÖã¬Óðٷֱȱíʾ£¬×îÉϲàÊÇ0£¬×îϲàÊÇ100¡£ÀýÈçÉèÖÃΪ50±íʾ´¹ֱ¾ÓÖУ¬20ÊÇƫÉϣ¬80ÔòÊÇƫÏ¡£ -* mirror: ¾µÏñ·­ת¡£Ìṩ2Öַ­תģʽ, ˮƽ·­תºʹ¹ֱ·­ת¡£ -* scale: ͼ²ã·Ŵó±¶Êý£¬1.0 ±íʾԭ´ó¡£ -* aspect_ratio: ͼ²㳤¿í±ȡ£1.0 ÊÇԭʼ±ÈÀý£¬´óÓڴËֵ±íʾÀ­³¤£¬СÓڴËֵ±íʾѹ±⡣ -* rotate: ͼ²ãÐýת¶ÈÊý¡£ -* transform_method: ÓÃÓÚͼ²ã·ŴóºÍÐýתµIJÉÑù·½·¨£¬°üÀ¨lanczos¡¢bicubic¡¢hamming¡¢bilinear¡¢boxºÍnearest¡£²»ͬµIJÉÑù·½·¨»áӰÏìºϳɵĻ­Öʺͻ­Ã洦Àíʱ¼䡣 -* anti_aliasing: ¿¹¾â³ݣ¬·¶Χ´Ó0-16£¬ÊýֵԽ´󣬾â³ÝԽ²»Ã÷Ïԡ£¹ý¸ߵÄÊýֵ½«ÏÔÖø½µµͽڵãµĴ¦ÀíËٶȡ£ -* [½ڵãע½â](#½ڵãע½â) +* background_image: 背景图像。 +* layer_image5: 用于合成的层图像。 +* layer_mask2,5: 层图像的遮罩。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 图层混合模式。 +* opacity: 不透明度。 +* x_percent: 图层在背景图上的水平位置,用百分比表示,最左侧是0,最右侧是100,可以是小于0或者超过100,那表示图层有部分内容在画面之外。 +* y_percent: 图层在背景图上的垂直位置,用百分比表示,最上侧是0,最下侧是100。例如设置为50表示垂直居中,20是偏上,80则是偏下。 +* mirror: 镜像翻转。提供2种翻转模式, 水平翻转和垂直翻转。 +* scale: 图层放大倍数,1.0 表示原大。 +* aspect_ratio: 图层长宽比。1.0 是原始比例,大于此值表示拉长,小于此值表示压扁。 +* rotate: 图层旋转度数。 +* transform_method: 用于图层放大和旋转的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。不同的采样方法会影响合成的画质和画面处理时间。 +* anti_aliasing: 抗锯齿,范围从0-16,数值越大,锯齿越不明显。过高的数值将显著降低节点的处理速度。 +* [节点注解](#节点注解) ### CropByMask -½«ͼƬ°´ÕÕmask·¶Χ²ÃÇУ¬¿ÉÉèÖÃËÄÖܱ߿ò±£Áô´óС¡£Õâ¸ö½ڵãÓë[RestoreCropBox](#RestoreCropBox)ºÍ[ImageScaleRestore](#ImageScaleRestore)ÅäºÏʹÓ㬿ÉÒԶÔͼƬµľֲ¿½øÐвÃÇУ¬·ŴóÐ޸ĺóÌù»Øԭ´¦¡£ +将图片按照mask范围裁切,可设置四周边框保留大小。这个节点与[RestoreCropBox](#RestoreCropBox)和[ImageScaleRestore](#ImageScaleRestore)配合使用,可以对图片的局部进行裁切,放大修改后贴回原处。 ![image](image/corp_by_mask_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/corp_by_mask_node.png) -* image5: ÊäÈëµÄͼÏñ¡£ -* mask_for_crop5: imageµÄÕÚÕ֣¬½«×Զ¯°´ÕÕÕÚÕַ¶Χ½øÐвÃÇС£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* detect: ̽²ⷽ·¨£¬min_bounding_rectÊÇ×îСÍâ½ӾØÐÎ, max_inscribed_rectÊÇ×î´óÄڽӾØÐΡ£ -* top_reserve: ²ÃÇж¥¶˱£Áô´óС¡£ -* bottom_reserve: ²ÃÇеײ¿±£Áô´óС¡£ -* left_reserve: ²ÃÇÐ×ó²ౣÁô´óС¡£ -* right_reserve: ²ÃÇÐÓҲౣÁô´óС¡£ -* [½ڵãע½â](#½ڵãע½â) +* image5: 输入的图像。 +* mask_for_crop5: image的遮罩,将自动按照遮罩范围进行裁切。 +* invert_mask: 是否反转遮罩。 +* detect: 探测方法,min_bounding_rect是最小外接矩形, max_inscribed_rect是最大内接矩形。 +* top_reserve: 裁切顶端保留大小。 +* bottom_reserve: 裁切底部保留大小。 +* left_reserve: 裁切左侧保留大小。 +* right_reserve: 裁切右侧保留大小。 +* [节点注解](#节点注解) -Êä³ö: -* croped_image: ²ÃÇкóµÄͼƬ¡£ -* croped_mask: ²ÃÇкóµÄÕÚÕ֡£ -* crop_box: ²ÃÇÐboxÊý¾ݣ¬ÔÚRestoreCropBox½ڵã»ָ´ʱʹÓᣠ-* box_preview: ²ÃÇÐλÖÃԤÀÀͼ£¬ºìɫÊÇ̽²⵽µķ¶Χ£¬ÂÌɫÊǼÓÉϱ£Áô±߿òºó²ÃÇеķ¶Χ¡£ +输出: +* croped_image: 裁切后的图片。 +* croped_mask: 裁切后的遮罩。 +* crop_box: 裁切box数据,在RestoreCropBox节点恢复时使用。 +* box_preview: 裁切位置预览图,红色是探测到的范围,绿色是加上保留边框后裁切的范围。 ### RestoreCropBox -½«±»[CropByMask](#CropByMask)²ÃÇкóµÄͼƬ»ָ´µ½ԭͼ¡£ +将被[CropByMask](#CropByMask)裁切后的图片恢复到原图。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/restore_crop_box_node.png) -* background_image: ²ÃÇÐǰµÄԭͼ¡£ -* croped_image5: ²ÃÇкóµÄͼƬ¡£Èç¹ûÖм侭¹ý·Ŵó´¦Àí£¬»ָ´ǰÐ轫³ߴ绹ԭ¡£ -* croped_mask2,5: ²ÃÇкóµÄÕÚÕ֡£ -* crop_box: ²ÃÇÐʱµÄboxÊý¾ݡ£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* [½ڵãע½â](#½ڵãע½â) +* background_image: 裁切前的原图。 +* croped_image5: 裁切后的图片。如果中间经过放大处理,恢复前需将尺寸还原。 +* croped_mask2,5: 裁切后的遮罩。 +* crop_box: 裁切时的box数据。 +* invert_mask: 是否反转遮罩。 +* [节点注解](#节点注解) ### ImageScaleRestore -ͼÏñËõ·š£´˽ڵã³ɶÔʹÓÃʱ£¬Ôڵڶþ¸ö½ڵã¿É×Զ¯»¹ԭͼÏñµ½ԭʼ´óС¡£ +图像缩放。此节点成对使用时,在第二个节点可自动还原图像到原始大小。 ![image](image/image_scale_restore_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_scale_restore_node.png) -* image5: ÊäÈëµÄͼÏñ¡£ -* mask2,5: ͼÏñµÄÕÚÕ֡£ -* original_size: ¿ÉѡÊäÈ룬ÓÃÓڻָ´ͼƬµ½ԭʼ´óС¡£ -* scale: Ëõ·űÈÀý¡£µ±ÓÐoriginal_sizeÊäÈ룬»òÕßscale_by_longest_sideÉèÖÃΪTrueʱ£¬´ËÏîÉèÖý«±»ºöÂԡ£ -* scale_by_longest_side: ÔÊÐí°´³¤±߳ߴçËõ·š£ -* longest_side: scale_by_longest_side±»ÉèÖÃΪTrueʱ£¬´ËÏ×÷ΪÊÇͼÏ񳤱ߵij¤¶ȡ£µ±ÓÐoriginal_sizeÊäÈëʱ£¬´ËÏîÉèÖý«±»ºöÂԡ£ -* [½ڵãע½â](#½ڵãע½â) +* image5: 输入的图像。 +* mask2,5: 图像的遮罩。 +* original_size: 可选输入,用于恢复图片到原始大小。 +* scale: 缩放比例。当有original_size输入,或者scale_by_longest_side设置为True时,此项设置将被忽略。 +* scale_by_longest_side: 允许按长边尺寸缩放。 +* longest_side: scale_by_longest_side被设置为True时,此项将作为是图像长边的长度。当有original_size输入时,此项设置将被忽略。 +* [节点注解](#节点注解) -Êä³ö: -* image: Ëõ·źóµÄͼÏñ¡£ -* mask: Èç¹ûÓÐmaskÊäÈ룬½«Êä³öËõ·źóµÄmask¡£ -* original_size: ͼÏñµÄԭʼ´óСÊý¾ݣ¬ÓÃÓںóÐø½ڵã½øÐлָ´¡£ +输出: +* image: 缩放后的图像。 +* mask: 如果有mask输入,将输出缩放后的mask。 +* original_size: 图像的原始大小数据,用于后续节点进行恢复。 ### ImageScaleRestoreV2 -ImageScaleRestoreµÄV2Éý¼¶°档 +ImageScaleRestore的V2升级版。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_scale_restore_v2_node.png) -ÔÚImageScaleRestore»ù´¡ÉÏ×öÁËÈçϸıä: -* scale_by: ÔÊÐí°´³¤±߻ò¶̱ßָ¶¨³ߴçËõ·š£ -* scale_by_length: scale_by±»ÉèÖÃΪ"longest"ʱ£¬´ËÏ×÷ΪÊÇͼÏ񳤱ߵij¤¶È; ÉèÖÃΪ"shortest"ʱ£¬×÷Ϊ¶̱ߵij¤¶ȡ£ +在ImageScaleRestore基础上做了如下改变: +* scale_by: 允许按长边或短边指定尺寸缩放。 +* scale_by_length: scale_by被设置为"longest"时,此项将作为是图像长边的长度; 设置为"shortest"时,作为短边的长度。 ### ImageMaskScaleAs -½«ͼÏñ»òÕÚÕÖËõ·ŵ½²ο¼ͼÏ񣨻òÕÚÕ֣©µĴóС¡£ +将图像或遮罩缩放到参考图像(或遮罩)的大小。 ![image](image/image_mask_scale_as_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_mask_scale_as_node.png) -* scale_as*: ²ο¼´óС¡£¿ÉÒÔÊÇͼÏñimage£¬Ҳ¿ÉÒÔÊÇÕÚÕÖmask¡£ -* image: ´ýËõ·ŵÄͼÏ񡣴ËѡÏîΪ¿ÉѡÊäÈ룬Èç¹ûûÓÐÊäÈ뽫Êä³ö´¿ºÚͼƬ¡£ -* mask: ´ýËõ·ŵÄÕÚÕ֡£´ËѡÏîΪ¿ÉѡÊäÈ룬Èç¹ûûÓÐÊäÈ뽫Êä³ö´¿ºÚÕÚÕ֡£ -* fit: Ëõ·Ż­·ù¿í¸߱Èģʽ¡£µ±ԭͼÓëËõ·ųߴ续·ù¿í¸߱ÈÀý²»һÖÂʱ£¬ÓÐ3ÖÖģʽ¿ÉÒÔѡÔñ, letterboxģʽ±£ÁôÍêÕûµĻ­·ù£¬¿հ״¦ÓúÚɫ²¹×㣻cropģʽ±£ÁôÍêÕûµĶ̱ߣ¬³¤±߳¬³ö²¿·ֽ«±»Çгý£»fillģʽ²»±£³ֻ­·ù±ÈÀý£¬¿í¸߸÷×ÔÌîÂú»­Ã档 -* method: Ëõ·ŵIJÉÑù·½·¨£¬°üÀ¨lanczos¡¢bicubic¡¢hamming¡¢bilinear¡¢boxºÍnearest¡£ +* scale_as*: 参考大小。可以是图像image,也可以是遮罩mask。 +* image: 待缩放的图像。此选项为可选输入,如果没有输入将输出纯黑图片。 +* mask: 待缩放的遮罩。此选项为可选输入,如果没有输入将输出纯黑遮罩。 +* fit: 缩放画幅宽高比模式。当原图与缩放尺寸画幅宽高比例不一致时,有3种模式可以选择, letterbox模式保留完整的画幅,空白处用黑色补足;crop模式保留完整的短边,长边超出部分将被切除;fill模式不保持画幅比例,宽高各自填满画面。 +* method: 缩放的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。 -*½öÏÞÊäÈëimageºÍmask, Èç¹ûǿÖƽÓÈëÆäËûÀàÐÍÊäÈ룬½«µ¼Ö½ڵã´íÎó¡£ +*仅限输入image和mask, 如果强制接入其他类型输入,将导致节点错误。 -Êä³ö: -* image: Èç¹ûÓÐimageÊäÈ룬½«Êä³öËõ·źóµÄͼÏñ¡£ -* mask: Èç¹ûÓÐmaskÊäÈ룬½«Êä³öËõ·źóµÄÕÚÕ֡£ -* original_size: ͼÏñµÄԭʼ´óСÊý¾ݣ¬ÓÃÓںóÐø½ڵã½øÐлָ´¡£ +输出: +* image: 如果有image输入,将输出缩放后的图像。 +* mask: 如果有mask输入,将输出缩放后的遮罩。 +* original_size: 图像的原始大小数据,用于后续节点进行恢复。 ### ImageScaleByAspectRatio -½«ͼÏñ»òÕÚÕְ´¿í¸߱ÈËõ·š£¿ÉÉèÖý«Ëõ·źóµijߴ簴8»òÕß16µı¶ÊýȡÕû£¬¿ɰ´³¤±߳ߴçËõ·š£ +将图像或遮罩按宽高比缩放。可设置将缩放后的尺寸按8或者16的倍数取整,可按长边尺寸缩放。 ![image](image/image_scale_by_aspect_ratio_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_scale_by_aspect_ratio_node.png) -* aspect_ratio: ¿í¸߱ȡ£´˴¦ÌṩÁ˼¸¸ö³£¼û»­·ù±ÈÀý¡£Ҳ¿Éѡ"original"±£³Öԭͼ±ÈÀý»òÕß"custom"×Զ¨Òå±ÈÀý¡£ -* proportional_width: ±ÈÀý¿í¡£Èç¹ûaspect_ratioѡÏÊÇ"custom"£¬´˴¦ÉèÖý«±»ºöÂԡ£ -* proportional_height: ±ÈÀý¸ߡ£Èç¹ûaspect_ratioѡÏÊÇ"custom"£¬´˴¦ÉèÖý«±»ºöÂԡ£ -* fit: Ëõ·Ż­·ù¿í¸߱Èģʽ¡£ÓÐ3ÖÖģʽ¿ÉÒÔѡÔñ, letterboxģʽ±£ÁôÍêÕûµĻ­·ù£¬¿հ״¦ÓúÚɫ²¹×㣻cropģʽ±£ÁôÍêÕûµĶ̱ߣ¬³¤±߳¬³ö²¿·ֽ«±»Çгý£»fillģʽ²»±£³ֻ­·ù±ÈÀý£¬¿í¸߸÷×ÔÌîÂú»­Ã档 -* method: Ëõ·ŵIJÉÑù·½·¨£¬°üÀ¨lanczos¡¢bicubic¡¢hamming¡¢bilinear¡¢boxºÍnearest¡£ -* round_to_multiple: ±¶ÊýȡÕû¡£ÀýÈçÉèÖÃΪ8£¬¿íº͸߽«ǿÖÆÉèÖÃΪ8µı¶Êý¡£ -* scale_by_longest_side: ÔÊÐí°´³¤±߳ߴçËõ·š£ -* longest_side: scale_by_longest_side±»ÉèÖÃΪTrueʱ£¬´ËÏ×÷ΪÊÇͼÏ񳤱ߵij¤¶ȡ£ +* aspect_ratio: 宽高比。此处提供了几个常见画幅比例。也可选"original"保持原图比例或者"custom"自定义比例。 +* proportional_width: 比例宽。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* proportional_height: 比例高。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* fit: 缩放画幅宽高比模式。有3种模式可以选择, letterbox模式保留完整的画幅,空白处用黑色补足;crop模式保留完整的短边,长边超出部分将被切除;fill模式不保持画幅比例,宽高各自填满画面。 +* method: 缩放的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。 +* round_to_multiple: 倍数取整。例如设置为8,宽和高将强制设置为8的倍数。 +* scale_by_longest_side: 允许按长边尺寸缩放。 +* longest_side: scale_by_longest_side被设置为True时,此项将作为是图像长边的长度。 -Êä³ö: -* image: Èç¹ûÓÐimageÊäÈ룬½«Êä³öËõ·źóµÄͼÏñ¡£ -* mask: Èç¹ûÓÐmaskÊäÈ룬½«Êä³öËõ·źóµÄÕÚÕ֡£ -* original_size: ͼÏñµÄԭʼ´óСÊý¾ݣ¬ÓÃÓںóÐø½ڵã½øÐлָ´¡£ +输出: +* image: 如果有image输入,将输出缩放后的图像。 +* mask: 如果有mask输入,将输出缩放后的遮罩。 +* original_size: 图像的原始大小数据,用于后续节点进行恢复。 ### ImageScaleByAspectRatioV2 -ImageScaleByAspectRatioµÄV2Éý¼¶°æ +ImageScaleByAspectRatio的V2升级版 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_scale_by_aspect_ratio_v2_node.png) -ÔÚImageScaleByAspectRatio»ù´¡ÉÏ×öÁËÈçϸıä: -* scale_to_side: ÔÊÐí°´³¤±߻ò¶̱ßָ¶¨³ߴçËõ·š£ -* scale_to_length: scale_by_side±»ÉèÖÃΪ"longest"ʱ£¬´ËÏ×÷ΪÊÇͼÏ񳤱ߵij¤¶È; ÉèÖÃΪ"shortest"ʱ£¬×÷Ϊ¶̱ߵij¤¶ȡ£ +在ImageScaleByAspectRatio基础上做了如下改变: +* scale_to_side: 允许按长边或短边指定尺寸缩放。 +* scale_to_length: scale_by_side被设置为"longest"时,此项将作为是图像长边的长度; 设置为"shortest"时,作为短边的长度。 ### ImageShift -ʹͼƬ²úÉúλÒơ£´˽ڵã֧³ÖλÒƽӷìÕÚÕֵÄÊä³ö£¬·½±ãÖÆ×÷Á¬ÐøÌùͼ¡£ +使图片产生位移。此节点支持位移接缝遮罩的输出,方便制作连续贴图。 ![image](image/image_shift_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_shift_node.png) -* image5: ÊäÈëµÄͼÏñ¡£ -* mask2,5: ͼÏñµÄÕÚÕ֡£ -* shift_x: λÒƵĺáÏò¾àÀ롣 -* shift_y: λÒƵÄ×ÝÏò¾àÀ롣 -* cyclic: λÒƳö½çµIJ¿·ÖÊǷñѭ»·¡£ -* background_color: ±³¾°ÑÕɫ¡£Èç¹ûcyclicÉèÖÃΪFalse,½«ʹÓÃÕâÀïµÄÉèÖÃ×÷Ϊ±³¾°ÑÕɫ¡£ -* border_mask_width: ½ӷìÕÚÕֿí¶ȡ£ -* border_mask_blur: ½ӷìÕÚÕÖģºý¡£ -* [½ڵãע½â](#½ڵãע½â) +* image5: 输入的图像。 +* mask2,5: 图像的遮罩。 +* shift_x: 位移的横向距离。 +* shift_y: 位移的纵向距离。 +* cyclic: 位移出界的部分是否循环。 +* background_color: 背景颜色。如果cyclic设置为False,将使用这里的设置作为背景颜色。 +* border_mask_width: 接缝遮罩宽度。 +* border_mask_blur: 接缝遮罩模糊。 +* [节点注解](#节点注解) ### ImageBlend -һ¸öÓÃÓںϳÉͼ²ãµļ򵥽ڵ㣬Ìṩ¶àÖֻìºÏģʽ¹©ѡÔ񣬿ÉÉèÖÃ͸Ã÷¶ȡ£ +一个用于合成图层的简单节点,提供多种混合模式供选择,可设置透明度。 ![image](image/image_blend_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_blend_node.png) -* background_image1: ±³¾°ͼÏñ¡£ -* layer_image1: ÓÃÓںϳɵIJãͼÏñ¡£ -* layer_mask1,2: ²ãͼÏñµÄÕÚÕ֡£ -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blend_mode3: ͼ²ã»ìºÏģʽ¡£ -* opacity: ²»͸Ã÷¶ȡ£ -* [½ڵãע½â](#½ڵãע½â) +* background_image1: 背景图像。 +* layer_image1: 用于合成的层图像。 +* layer_mask1,2: 层图像的遮罩。 +* invert_mask: 是否反转遮罩。 +* blend_mode3: 图层混合模式。 +* opacity: 不透明度。 +* [节点注解](#节点注解) ### ImageOpacity -µ÷ÕûͼÏñ²»͸Ã÷¶ȡ£ +调整图像不透明度。 ![image](image/image_opacity_example.png) -½ڵãѡÏî˵Ã÷: -* image5: ͼÏñÊäÈ룬֧³ÖRGBºÍRGBAÊäÈ롣 -* mask2,5: ÕÚÕÖÊäÈ롣 -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* opacity: ²»͸Ã÷¶ȡ£ -* [½ڵãע½â](#½ڵãע½â) +节点选项说明: +* image5: 图像输入,支持RGB和RGBA输入。 +* mask2,5: 遮罩输入。 +* invert_mask: 是否反转遮罩。 +* opacity: 不透明度。 +* [节点注解](#节点注解) ### ColorPicker -ÔÚɫ°åÉÏѡȡÑÕɫ²¢Êä³ö¡£ -¸Ä×Ô[mtb nodes](https://github.com/melMass/comfy_mtb)µÄweb extensions¡£ +在色板上选取颜色并输出。 +改自[mtb nodes](https://github.com/melMass/comfy_mtb)的web extensions。 ![image](image/color_picker.png) -½ڵãѡÏî˵Ã÷: -* mode£º Êä³ö¸ñʽ£¬¿ÉѡʮÁù½øÖÆ(HEX)»òʮ½øÖÆ(DEC)¡£ +节点选项说明: +* mode: 输出格式,可选十六进制(HEX)或十进制(DEC)。 -Êä³ö: -* value: ×ַû´®¸ñʽ¡£ +输出: +* value: 字符串格式。 ### GetColorTone -´ÓͼƬÖлñȡÖ÷ÑÕɫ»òƽ¾ùɫ¡£ +从图片中获取主颜色或平均色。 ![image](image/get_color_tone_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/get_color_tone_node.png) -* mode£º ģʽ£¬ÓÐÁ½ÖֿÉѡÔñ£¬Ö÷ÑÕɫmain_colorºÍƽ¾ùɫaverage¡£ +* mode: 模式,有两种可选择,主颜色main_color和平均色average。 -Êä³ö: -* RGB color in HEX: ʹÓÃ16½øÖÆRGB×ַû´®¸ñʽÃèÊö£¬ÀýÈç '#FA3D86'¡£ -* HSV color in list: HSVÑÕɫֵ£¬ʹÓÃlist¸ñʽÃèÊö¡£ +输出: +* RGB color in HEX: 使用16进制RGB字符串格式描述,例如 '#FA3D86'。 +* HSV color in list: HSV颜色值,使用list格式描述。 ### ExtendCanvas -À©չ»­²¼¡£ +扩展画布。 ![image](image/extend_canvas_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/extend_canvas_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* top: ¶¥²¿À©չֵ¡£ -* bottom: µײ¿À©չֵ¡£ -* left: ×ó²àÀ©չֵ¡£ -* right: ÓҲàÀ©չֵ¡£ -* color; »­²¼ÑÕɫ +* invert_mask: 是否反转遮罩。 +* top: 顶部扩展值。 +* bottom: 底部扩展值。 +* left: 左侧扩展值。 +* right: 右侧扩展值。 +* color; 画布颜色 ### XY to Percent ![image](image/xy2percent_example.png) -½«¾ø¶Ô×ø±êת»»Ϊ°ٷֱÈ×ø±ꡣ +将绝对坐标转换为百分比坐标。 ![image](image/xy2percent_node.png) -½ڵãѡÏî˵Ã÷: -* x: ×ø±êxֵ¡£ -* y: ×ø±êyֵ¡£ +节点选项说明: +* x: 坐标x值。 +* y: 坐标y值。 ### LayerImageTransform ![image](image/layer_image_transform_example.png) -Õâ¸ö½ڵãÓÃÓڵ¥¶À¶Ôlayer_image½øÐб任£¬¿ɸıä´óС£¬Ðýת£¬¸ı䳤¿í±ÈÒԼ°¾µÏñ·­ת¡£ +这个节点用于单独对layer_image进行变换,可改变大小,旋转,改变长宽比以及镜像翻转。 ![image](image/layer_image_transform_node.png) -½ڵãѡÏî˵Ã÷: -* x: ×ø±êxֵ¡£ -* y: ×ø±êyֵ¡£ -* mirror: ¾µÏñ·­ת¡£Ìṩ2Öַ­תģʽ, ˮƽ·­תºʹ¹ֱ·­ת¡£ -* scale: ͼ²ã·Ŵó±¶Êý£¬1.0 ±íʾԭ´ó¡£ -* aspect_ratio: ͼ²㳤¿í±ȡ£1.0 ÊÇԭʼ±ÈÀý£¬´óÓڴËֵ±íʾÀ­³¤£¬СÓڴËֵ±íʾѹ±⡣ -* rotate: ͼ²ãÐýת¶ÈÊý¡£ -* transform_method: ÓÃÓÚͼ²ã·ŴóºÍÐýתµIJÉÑù·½·¨£¬°üÀ¨lanczos¡¢bicubic¡¢hamming¡¢bilinear¡¢boxºÍnearest¡£²»ͬµIJÉÑù·½·¨»áӰÏìºϳɵĻ­Öʺͻ­Ã洦Àíʱ¼䡣 -* anti_aliasing: ¿¹¾â³ݣ¬·¶Χ´Ó0-16£¬ÊýֵԽ´󣬾â³ÝԽ²»Ã÷Ïԡ£¹ý¸ߵÄÊýֵ½«ÏÔÖø½µµͽڵãµĴ¦ÀíËٶȡ£ +节点选项说明: +* x: 坐标x值。 +* y: 坐标y值。 +* mirror: 镜像翻转。提供2种翻转模式, 水平翻转和垂直翻转。 +* scale: 图层放大倍数,1.0 表示原大。 +* aspect_ratio: 图层长宽比。1.0 是原始比例,大于此值表示拉长,小于此值表示压扁。 +* rotate: 图层旋转度数。 +* transform_method: 用于图层放大和旋转的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。不同的采样方法会影响合成的画质和画面处理时间。 +* anti_aliasing: 抗锯齿,范围从0-16,数值越大,锯齿越不明显。过高的数值将显著降低节点的处理速度。 ### LayerMaskTransform -ÓëLayerImageTransformÀàËƣ¬Õâ¸ö½ڵãÓÃÓڵ¥¶À¶Ôlayer_mask½øÐб任£¬¿ɸıä´óС£¬Ðýת£¬¸ı䳤¿í±ÈÒԼ°¾µÏñ·­ת¡£ +与LayerImageTransform类似,这个节点用于单独对layer_mask进行变换,可改变大小,旋转,改变长宽比以及镜像翻转。 ![image](image/layer_mask_transform_node.png) -½ڵãѡÏî˵Ã÷: -* x: ×ø±êxֵ¡£ -* y: ×ø±êyֵ¡£ -* mirror: ¾µÏñ·­ת¡£Ìṩ2Öַ­תģʽ, ˮƽ·­תºʹ¹ֱ·­ת¡£ -* scale: ͼ²ã·Ŵó±¶Êý£¬1.0 ±íʾԭ´ó¡£ -* aspect_ratio: ͼ²㳤¿í±ȡ£1.0 ÊÇԭʼ±ÈÀý£¬´óÓڴËֵ±íʾÀ­³¤£¬СÓڴËֵ±íʾѹ±⡣ -* rotate: ͼ²ãÐýת¶ÈÊý¡£ -* transform_method: ÓÃÓÚͼ²ã·ŴóºÍÐýתµIJÉÑù·½·¨£¬°üÀ¨lanczos¡¢bicubic¡¢hamming¡¢bilinear¡¢boxºÍnearest¡£²»ͬµIJÉÑù·½·¨»áӰÏìºϳɵĻ­Öʺͻ­Ã洦Àíʱ¼䡣 -* anti_aliasing: ¿¹¾â³ݣ¬·¶Χ´Ó0-16£¬ÊýֵԽ´󣬾â³ÝԽ²»Ã÷Ïԡ£¹ý¸ߵÄÊýֵ½«ÏÔÖø½µµͽڵãµĴ¦ÀíËٶȡ£ +节点选项说明: +* x: 坐标x值。 +* y: 坐标y值。 +* mirror: 镜像翻转。提供2种翻转模式, 水平翻转和垂直翻转。 +* scale: 图层放大倍数,1.0 表示原大。 +* aspect_ratio: 图层长宽比。1.0 是原始比例,大于此值表示拉长,小于此值表示压扁。 +* rotate: 图层旋转度数。 +* transform_method: 用于图层放大和旋转的采样方法,包括lanczos、bicubic、hamming、bilinear、box和nearest。不同的采样方法会影响合成的画质和画面处理时间。 +* anti_aliasing: 抗锯齿,范围从0-16,数值越大,锯齿越不明显。过高的数值将显著降低节点的处理速度。 ### ColorImage ![image](image/color_image_example.png) -Éú³ÉһÕÅָ¶¨ÑÕɫºʹóСµÄͼƬ¡£ +生成一张指定颜色和大小的图片。 ![image](image/color_image_node.png) -½ڵãѡÏî˵Ã÷: -* width: ͼÏñ¿í¶ȡ£ -* height: ͼÏñ¸߶ȡ£ -* color4: ÑÕɫ¡£ +节点选项说明: +* width: 图像宽度。 +* height: 图像高度。 +* color4: 颜色。 ### GradientImage ![image](image/gradient_image_example.png) -Éú³ÉһÕÅָ¶¨´óСºÍָ¶¨ÑÕɫ½¥±äµÄͼƬ¡£ +生成一张指定大小和指定颜色渐变的图片。 ![image](image/gradient_image_node.png) -½ڵãѡÏî˵Ã÷: -* width: ͼÏñ¿í¶ȡ£ -* height: ͼÏñ¸߶ȡ£ -* angle: ½¥±ä½Ƕȡ£ -* start_color4: ¿ªʼ¶ËÑÕɫ¡£ -* end_color4: ½áÊø¶ËÑÕɫ¡£ +节点选项说明: +* width: 图像宽度。 +* height: 图像高度。 +* angle: 渐变角度。 +* start_color4: 开始端颜色。 +* end_color4: 结束端颜色。 ### TextImage ![image](image/text_image_example.png) -´ÓÎÄ×ÖÉú³ÉͼƬÒԼ°ÕÚÕ֡£֧³Ö×ּä¾àÐмä¾àµ÷Õû£¬ºáÅÅÊúÅŵ÷Õû£¬¿ÉÉèÖÃÎÄ×ֵÄËæ»ú±仯£¬°üÀ¨´óСºÍλÖõÄËæ»ú±仯¡£ +从文字生成图片以及遮罩。支持字间距行间距调整,横排竖排调整,可设置文字的随机变化,包括大小和位置的随机变化。 ![image](image/text_image_node.png) -½ڵãѡÏî˵Ã÷: -* size_as*: ´˴¦ÊäÈëͼÏñ»òÕÚÕ֣¬½«°´ÕÕÆä³ߴçÉú³ÉÊä³öͼÏñºÍÕÚÕ֡£עÒ⣬´ËÊäÈëÓÅÏȼ¶¸ßÓÚÏÂÃæµÄwidthºÍheight¡£ -* font_file**: ÕâÀïÁгöÁËfontÎļþ¼ÐÖпÉÓõÄ×ÖÌåÎļþÁбí£¬ѡÖеÄ×ÖÌåÎļþ½«±»ÓÃÀ´Éú³ÉͼÏñ¡£ -* spacing: ×ּä¾à,ÒÔÏñËØΪµ¥λ¡£ -* leading: Ðмä¾à,ÒÔÏñËØΪµ¥λ¡£ -* horizontal_border: ²à±߱߾ࡣ´˴¦Êýֵ±íʾµÄÊǰٷֱȣ¬ÀýÈç50±íʾÆðµãλÓÚÁ½²àµÄÕýÖÐÑ롣Èç¹ûÎÄ×ÖÊǺáÅţ¬ÊÇ×ó²à±߾࣬ÊúÅÅÔòÊÇÓҲà±߾ࡣ -* vertical_border: ¶¥²¿±߾ࡣ´˴¦Êýֵ±íʾµÄÊǰٷֱȣ¬ÀýÈç10±íʾÆðµãλÓھඥ²¿10%µÄλÖᣠ-* scale: ÎÄ×Ö×ÜÌå´óС¡£ÎÄ×ֵijõʼ´óСÊǸù¾ݻ­Ãæ³ߴçºÍÎÄ×ÖÄÚÈÝ×Զ¯¼ÆË㣬ĬÈÏÒÔ×µÄÐлòÕßÁÐÊÊÅ仭Ãæ¿í»òÕ߸ߡ£µ÷Õû´˴¦Êýֵ½«ÕûÌå·ŴóºÍËõСÎÄ×֡£´˴¦Êýֵ±íʾµÄÊǰٷֱȣ¬ÀýÈç60±íʾËõ·ŵ½60%¡£ -* variation_range: ×ַûËæ»ú±仯·¶Χ¡£´ËÊýֵ´óÓÚ0ʱ£¬×ַû½«²úÉú´óСºÍλÖõÄËæ»ú±仯£¬ÊýֵԽ´󣬱仯·ù¶ÈԽ´ó¡£ -* variation_seed: Ëæ»ú±仯µÄÖÖ×ӡ£¹̶¨´ËÊýֵ£¬ÿ´βúÉúµĵ¥¸öÎÄ×ֵı仯²»»á¸ı䡣 -* layout: ÎÄ×ÖÅŰ档ÓкáÅźÍÊúÅſÉѡÔñ¡£ -* width: »­ÃæµĿí¶ȡ£Èç¹ûÓÐsize_asÊäÈ룬´ËÉèÖý«±»ºöÂԡ£ -* height: »­Ãæµĸ߶ȡ£Èç¹ûÓÐsize_asÊäÈ룬´ËÉèÖý«±»ºöÂԡ£ -* text_color: ÎÄ×ÖÑÕɫ¡£ -* background_color: ±³¾°ÑÕɫ¡£ +节点选项说明: +* size_as*: 此处输入图像或遮罩,将按照其尺寸生成输出图像和遮罩。注意,此输入优先级高于下面的width和height。 +* font_file**: 这里列出了font文件夹中可用的字体文件列表,选中的字体文件将被用来生成图像。 +* spacing: 字间距,以像素为单位。 +* leading: 行间距,以像素为单位。 +* horizontal_border: 侧边边距。此处数值表示的是百分比,例如50表示起点位于两侧的正中央。如果文字是横排,是左侧边距,竖排则是右侧边距。 +* vertical_border: 顶部边距。此处数值表示的是百分比,例如10表示起点位于距顶部10%的位置。 +* scale: 文字总体大小。文字的初始大小是根据画面尺寸和文字内容自动计算,默认以最长的行或者列适配画面宽或者高。调整此处数值将整体放大和缩小文字。此处数值表示的是百分比,例如60表示缩放到60%。 +* variation_range: 字符随机变化范围。此数值大于0时,字符将产生大小和位置的随机变化,数值越大,变化幅度越大。 +* variation_seed: 随机变化的种子。固定此数值,每次产生的单个文字的变化不会改变。 +* layout: 文字排版。有横排和竖排可选择。 +* width: 画面的宽度。如果有size_as输入,此设置将被忽略。 +* height: 画面的高度。如果有size_as输入,此设置将被忽略。 +* text_color: 文字颜色。 +* background_color: 背景颜色。 -*½öÏÞÊäÈëimageºÍmask, Èç¹ûǿÖƽÓÈëÆäËûÀàÐÍÊäÈ룬½«µ¼Ö½ڵã´íÎó¡£ +*仅限输入image和mask, 如果强制接入其他类型输入,将导致节点错误。 -**fontÎļþ¼ÐÔÚresource_dir.iniÖж¨Ò壬Õâ¸öÎļþλÓڲå¼þ¸ùĿ¼Ï¡£ÓÃÎı¾±༭Èí¼þ´򿪣¬Õҵ½¡°FONT_dir=¡±¿ªͷµÄÕâһÐУ¬±༭¡°=¡±֮ºóΪ×Զ¨ÒåÎļþ¼Ð·¾¶Ãû¡£Õâ¸öÎļþ¼ÐÀïÃæËùÓеÄ.ttfºÍ.otfÎļþ½«ÔÚComfyUI³õʼ»¯ʱ±»Êռ¯²¢ÏÔʾÔڽڵãµÄÁбíÖС£Èç¹ûiniÖÐÉ趨µÄÎļþ¼ÐÎÞЧ£¬½«ÆôÓòå¼þ×ԴøµÄfontÎļþ¼С£ +**font文件夹在resource_dir.ini中定义,这个文件位于插件根目录下。用文本编辑软件打开,找到“FONT_dir=”开头的这一行,编辑“=”之后为自定义文件夹路径名。这个文件夹里面所有的.ttf和.otf文件将在ComfyUI初始化时被收集并显示在节点的列表中。如果ini中设定的文件夹无效,将启用插件自带的font文件夹。 +### LaMa +![image](image/lama_example.png) +根据图像遮罩擦除物体。本节点是对[IOPaint](https://www.iopaint.com)的封装,由 SOTA AI 模型提供支持。 +提供[LaMa](#https://github.com/advimman/lama), [LDM](https://github.com/CompVis/latent-diffusion), [ZITS](https://github.com/DQiaole/ZITS_inpainting),[MAT](https://github.com/fenglinglwb/MAT), [FcF](https://github.com/SHI-Labs/FcF-Inpainting), [Manga](https://github.com/msxie92/MangaInpainting) 模型以及 OpenCV 擦除方法。请查看链接了解各个模型的介绍。 +请下载模型文件 [lama models(百度网盘)](https://pan.baidu.com/s/1LllR9TJHP1G9uEwWT3Mvkg?pwd=tvzv) 或者 [lama models(Google Drive)](https://drive.google.com/drive/folders/1Aq0a4sybb3SRxi7j1e1_ZbBRjaWDdP9e?usp=sharing), 将文件放到```ComfyUI/models/lama``` + +节点选项说明: +![image](image/lama_node.png) +* lama_model: 选择模型或方法。 +* device: 在正确安装torch和Nvidia CUDA驱动程序后,使用cuda将明显提高运行速度。 +* invert_mask: 是否反转遮罩。 +* grow: 遮罩扩张幅度。正值是向外扩张,负值是向内收缩。 +* blur: 遮罩模糊幅度。 + ### ImageChannelSplit ![image](image/image_channel_split_example.png) -½«ͼÏñͨµÀ²ð·ÖΪµ¥¶ÀµÄͼƬ¡£ +将图像通道拆分为单独的图片。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_channel_split_node.png) -* mode: ͨµÀģʽ¡£°üº¬RGBA, YCbCr, LABºÍHSV¡£ +* mode: 通道模式。包含RGBA, YCbCr, LAB和HSV。 ### ImageChannelMerge ![image](image/image_channel_merge_example.png) -½«¸÷ͨµÀºϲ¢ΪһÕÅͼƬ¡£ +将各通道合并为一张图片。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_channel_merge_node.png) -* mode: ͨµÀģʽ¡£°üº¬RGBA, YCbCr, LABºÍHSV¡£ +* mode: 通道模式。包含RGBA, YCbCr, LAB和HSV。 ### ImageRemoveAlpha ![image](image/image_remove_alpha_example.png) -ÒƳýͼƬµÄalphaͨµÀ£¬½«ͼƬת»»ΪRGBģʽ¡£¿ÉѡÔñÌî³䱳¾°ÒԼ°ÉèÖñ³¾°ÑÕɫ¡£ +移除图片的alpha通道,将图片转换为RGB模式。可选择填充背景以及设置背景颜色。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_remove_alpha_node.png) -* fill_background: ÊǷñÌî³䱳¾°¡£ -* background_color4: ±³¾°ÑÕɫ¡£ +* fill_background: 是否填充背景。 +* background_color4: 背景颜色。 ### ImageCombineAlpha ![image](image/image_combine_alpha_node.png) -½«ͼƬÓëÕÚÕֺϲ¢Ϊ°üº¬alphaͨµÀµÄRGBAģʽµÄͼƬ¡£ +将图片与遮罩合并为包含alpha通道的RGBA模式的图片。 ### ImageAutoCrop ![image](image/image_auto_crop_example.png) -×Զ¯¿Ùͼ²¢°´ÕÕÕÚÕֲÃÇÐͼƬ¡£¿Éָ¶¨Éú³ÉͼƬµı³¾°ÑÕɫ¡¢³¤¿í±ȺʹóС¡£Õâ¸ö½ڵãÊÇΪÉú³ÉѵÁ·ģÐ͵ÄͼƬËزĶøÉè¼Ƶġ£ -*Çë²ÎÕÕ [SegmentAnythingUltra](#SegmentAnythingUltra) ºÍ [RemBgUltra](#RemBgUltra) ½ڵãµÄģÐͰ²װ·½·¨°²װģÐ͡£ +自动抠图并按照遮罩裁切图片。可指定生成图片的背景颜色、长宽比和大小。这个节点是为生成训练模型的图片素材而设计的。 +*请参照 [SegmentAnythingUltra](#SegmentAnythingUltra) 和 [RemBgUltra](#RemBgUltra) 节点的模型安装方法安装模型。 -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/image_auto_crop_node.png) -* background_color4: ±³¾°ÑÕɫ¡£ -* aspect_ratio: Êä³öµĿí¸߱ȡ£ÕâÀïÌṩÁ˳£¼ûµĻ­·ù±ÈÀý£¬ "custom"Ϊ×Զ¨Òå±ÈÀý¡£ -* proportional_width: ±ÈÀý¿í¡£Èç¹ûaspect_ratioѡÏÊÇ"custom"£¬´˴¦ÉèÖý«±»ºöÂԡ£ -* proportional_height: ±ÈÀý¸ߡ£Èç¹ûaspect_ratioѡÏÊÇ"custom"£¬´˴¦ÉèÖý«±»ºöÂԡ£ -* scale_by_longest_side: ÔÊÐí°´³¤±߳ߴçËõ·š£ -* longest_side: scale_by_longest_side±»ÉèÖÃΪTrueʱ£¬´ËÏ×÷ΪÊÇͼÏ񳤱ߵij¤¶ȡ£ -* detect: ̽²ⷽ·¨£¬min_bounding_rectÊÇ×îСÍâ½ӾØÐÎ, max_inscribed_rectÊÇ×î´óÄڽӾØÐΡ£ -* border_reserve: ±£Áô±߿ò¡£ÔÚ̽²⵽µÄÕÚÕÖÖ÷ÌåÇøÓò֮ÍâÀ©չ²ÃÇз¶Χ¡£ -* ultra_detail_range: ÕÚÕֱßԵ³¬¾«ϸ´¦Àí·¶Χ£¬0Ϊ²»´¦Àí£¬¿ÉÒԽÚʡÉú³Éʱ¼䡣 -* matting_method: Éú³ÉÕÚÕֵķ½·¨¡£ÓÐSegment AnythingºÍ RMBG 1.4Á½Öַ½·¨¡£RMBG 1.4ÔËÐÐËٶȸü¿졣 -* sam_model: ´˴¦ѡÔñSegment AnythingËùʹÓõÄsamģÐ͡£ -* grounding_dino_model: ´˴¦ѡÔñSegment AnythingËùʹÓõÄgrounding_dinoģÐ͡£ -* sam_threshold: Segment AnythingµÄãÐֵ¡£ -* sam_prompt: Segment AnythingµÄÌáʾ´ʡ£ +* background_color4: 背景颜色。 +* aspect_ratio: 输出的宽高比。这里提供了常见的画幅比例, "custom"为自定义比例。 +* proportional_width: 比例宽。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* proportional_height: 比例高。如果aspect_ratio选项不是"custom",此处设置将被忽略。 +* scale_by_longest_side: 允许按长边尺寸缩放。 +* longest_side: scale_by_longest_side被设置为True时,此项将作为是图像长边的长度。 +* detect: 探测方法,min_bounding_rect是最小外接矩形, max_inscribed_rect是最大内接矩形。 +* border_reserve: 保留边框。在探测到的遮罩主体区域之外扩展裁切范围。 +* ultra_detail_range: 遮罩边缘超精细处理范围,0为不处理,可以节省生成时间。 +* matting_method: 生成遮罩的方法。有Segment Anything和 RMBG 1.4两种方法。RMBG 1.4运行速度更快。 +* sam_model: 此处选择Segment Anything所使用的sam模型。 +* grounding_dino_model: 此处选择Segment Anything所使用的grounding_dino模型。 +* sam_threshold: Segment Anything的阈值。 +* sam_prompt: Segment Anything的提示词。 -Êä³ö: -cropped_image: ²ÃÇв¢¸ü»»±³¾°ºóµÄͼÏñ¡£ -box_preview: ²ÃÇÐλÖÃԤÀÀ¡£ -cropped_mask: ²ÃÇкóµÄÕÚÕ֡£ +输出: +cropped_image: 裁切并更换背景后的图像。 +box_preview: 裁切位置预览。 +cropped_mask: 裁切后的遮罩。 ### GetImageSize ![image](image/get_image_size_node.png) -»ñȡͼƬµĿí¶Ⱥ͸߶ȡ£ +获取图片的宽度和高度。 -Êä³ö: -* width: ͼÏñ¿í¶ȡ£ -* height: ͼÏñ¸߶ȡ£ -* original_size: ͼÏñµÄԭʼ´óСÊý¾ݣ¬ÓÃÓںóÐø½ڵã½øÐлָ´¡£ +输出: +* width: 图像宽度。 +* height: 图像高度。 +* original_size: 图像的原始大小数据,用于后续节点进行恢复。 ### PrintInfo ![image](image/print_info_node.png) -ÓÃÓڸø¹¤×÷Á÷µ÷ÊÔÌṩ¸¨Öú¡£µ±ÔËÐÐʱ£¬ÈκνÓÉÏÕâ¸ö½ڵãµĶÔÏóµÄÊôÐԽ«±»´òӡµ½¿ØÖÆ̨¡£ +用于给工作流调试提供辅助。当运行时,任何接上这个节点的对象的属性将被打印到控制台。 -Õâ¸ö½ڵãÔÊÐíÈÎÒâÀàÐ͵ÄÊäÈ롣 +这个节点允许任意类型的输入。 @@ -673,210 +726,210 @@ cropped_mask: ![image](image/layermask_nodes.png) ### MaskBoxDetect -̽²âmaskËùÔÚÇøÓ򣬲¢Êä³öλÖúʹóС¡£ +探测mask所在区域,并输出位置和大小。 ![image](image/mask_box_detect_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_box_detect_node.png) -* detect: ̽²ⷽ·¨£¬min_bounding_rectÊÇ×îСÍâ½ӾØÐÎ, max_inscribed_rectÊÇ×î´óÄڽӾØÐΡ£ -* x_adjust: ÐÞÕý̽²â֮ºóµÄˮƽƫÒơ£ -* y_adjust: ÐÞÕý̽²â֮ºóµĴ¹ֱƫÒơ£ -* scale_adjust: ÐÞÕý̽²â֮ºóµÄËõ·ÅƫÒơ£ +* detect: 探测方法,min_bounding_rect是最小外接矩形, max_inscribed_rect是最大内接矩形。 +* x_adjust: 修正探测之后的水平偏移。 +* y_adjust: 修正探测之后的垂直偏移。 +* scale_adjust: 修正探测之后的缩放偏移。 -Êä³ö£º -* box_preview: ̽²â½á¹ûԤÀÀͼ¡£ºìɫ±íʾ̽²⵽µĽá¹û£¬ÂÌɫ±íʾ¼ÓÉÏÐÞÕýºóµÄÊä³ö½á¹û¡£ -* x_percent: ˮƽλÖÃÒ԰ٷֱÈÊä³ö¡£ -* y_percent: ´¹ֱλÖÃÒ԰ٷֱÈÊä³ö¡£ -* width: ¿í¶ÈÊä³ö¡£ -* height: ¸߶ÈÊä³ö¡£ -* x: ×óÉϽÇλÖÃx×ø±êÊä³ö¡£ -* y: ×óÉϽÇλÖÃy×ø±êÊä³ö¡£ +输出: +* box_preview: 探测结果预览图。红色表示探测到的结果,绿色表示加上修正后的输出结果。 +* x_percent: 水平位置以百分比输出。 +* y_percent: 垂直位置以百分比输出。 +* width: 宽度输出。 +* height: 高度输出。 +* x: 左上角位置x坐标输出。 +* y: 左上角位置y坐标输出。 ### SegmentAnythingUltra -¶Ô[ComfyUI Segment Anything](https://github.com/storyicon/comfyui_segment_anything)µĸĽø£¬½áºÏÁËspacepxlµÄ[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)µÄAlpha Matte½ڵ㣬ʹÕÚÕÖÓиü¾ßϸ½ڵıßԵ¡£ +对[ComfyUI Segment Anything](https://github.com/storyicon/comfyui_segment_anything)的改进,结合了spacepxl的[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)的Alpha Matte节点,使遮罩有更具细节的边缘。 -*Çë²ÎÕÕComfyUI Segment Anythingµİ²װ·½·¨°²װģÐ͡£Èç¹ûÒѾ­Õýȷ°²װÁËComfyUI Segment Anything£¬¿ÉÌø¹ý´˲½Ö衣 -* ´Ó [ÕâÀï](https://huggingface.co/bert-base-uncased/tree/main) ÏÂÔØ config.json£¬model.safetensors£¬tokenizer_config.json£¬tokenizer.json ºÍ vocab.txt 5¸öÎļþµ½ ```ComfyUI/models/bert-base-uncased```Îļþ¼С£ -* ÏÂÔØ [GroundingDINO_SwinT_OGC config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinT_OGC.cfg.py), [GroundingDINO_SwinT_OGC model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth), -[GroundingDINO_SwinB config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinB.cfg.py), [GroundingDINO_SwinB model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swinb_cogcoor.pth) µ½ ```ComfyUI/models/grounding-dino```Îļþ¼С£ -* ÏÂÔØ [sam_vit_h](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth)£¬[sam_vit_l](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth), +*请参照ComfyUI Segment Anything的安装方法安装模型。如果已经正确安装了ComfyUI Segment Anything,可跳过此步骤。 +* 从 [这里](https://huggingface.co/bert-base-uncased/tree/main) 下载 config.json,model.safetensors,tokenizer_config.json,tokenizer.json 和 vocab.txt 5个文件到 ```ComfyUI/models/bert-base-uncased```文件夹。 +* 下载 [GroundingDINO_SwinT_OGC config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinT_OGC.cfg.py), [GroundingDINO_SwinT_OGC model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swint_ogc.pth), +[GroundingDINO_SwinB config file](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/GroundingDINO_SwinB.cfg.py), [GroundingDINO_SwinB model](https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/groundingdino_swinb_cogcoor.pth) 到 ```ComfyUI/models/grounding-dino```文件夹。 +* 下载 [sam_vit_h](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth),[sam_vit_l](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth), [sam_vit_b](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth), [sam_hq_vit_h](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth), [sam_hq_vit_l](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth), [sam_hq_vit_b](https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth), -[mobile_sam](https://github.com/ChaoningZhang/MobileSAM/blob/master/weights/mobile_sam.pt) Õ⼸¸öÎļþµ½```ComfyUI/models/sams```Îļþ¼С£ +[mobile_sam](https://github.com/ChaoningZhang/MobileSAM/blob/master/weights/mobile_sam.pt) 这几个文件到```ComfyUI/models/sams```文件夹。 ![image](image/segment_anything_ultra_compare.png) ![image](image/segment_anything_ultra_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/segment_anything_ultra_node.png) -* sam_model: ѡÔñSAMģÐ͡£ -* ground_dino_model: ѡÔñGrounding DINOģÐ͡£ -* threshold: SAMãÐֵ¡£ -* detail_range: ±ßԵϸ½ڷ¶Χ¡£ -* black_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* white_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* process_detail: ´˴¦ÉèΪFalse½«Ìø¹ý±ßԵ´¦ÀíÒԽÚʡÔËÐÐʱ¼䡣 -* prompt: SAMµÄpromptÊäÈ롣 +* sam_model: 选择SAM模型。 +* ground_dino_model: 选择Grounding DINO模型。 +* threshold: SAM阈值。 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘黑色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 +* prompt: SAM的prompt输入。 ### RemBgUltra -ȥ³ý±³¾°¡£ÓëÀàËƵı³¾°ÒƳý½ڵãÏà±ȣ¬Õâ¸ö½ڵã¾ßÓг¬¸ߵıßԵϸ½ڡ£ -±¾½ڵã½áºÏÁËspacepxlµÄ[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)µÄAlpha Matte½ڵ㣬ÒԼ°ZHO-ZHO-ZHOµÄ[ComfyUI-BRIA_AI-RMBG](https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG)µĹ¦Äܡ£ +去除背景。与类似的背景移除节点相比,这个节点具有超高的边缘细节。 +本节点结合了spacepxl的[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)的Alpha Matte节点,以及ZHO-ZHO-ZHO的[ComfyUI-BRIA_AI-RMBG](https://github.com/ZHO-ZHO-ZHO/ComfyUI-BRIA_AI-RMBG)的功能。 -*½«[BRIA Background Removal v1.4](https://huggingface.co/briaai/RMBG-1.4)ģÐÍÎļþ(model.pth)ÏÂÔØÖÁ```ComfyUI/models/rmbg/RMBG-1.4```Îļþ¼С£¸ÃģÐÍÓÉ BRIA AI ¿ª·¢£¬¿É×÷Ϊ·ÇÉÌҵÓÃ;µĿªԴģÐ͡£ +*将[BRIA Background Removal v1.4](https://huggingface.co/briaai/RMBG-1.4)模型文件(model.pth)下载至```ComfyUI/models/rmbg/RMBG-1.4```文件夹。该模型由 BRIA AI 开发,可作为非商业用途的开源模型。 -**ÏÂÔØģÐͺ󣬽¨ÒéÔÚComfyUI/extra_model_paths.yamlÖÐÌí¼ÓһÐÐ'rmbg: models/rmbg/RMBG-1.4'¡£(´˲½Öè·DZØÐ룩 +**下载模型后,建议在ComfyUI/extra_model_paths.yaml中添加一行'rmbg: models/rmbg/RMBG-1.4'。(此步骤非必须) ![image](image/rembg_ultra_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/rembg_ultra_node.png) -* detail_range: ±ßԵϸ½ڷ¶Χ¡£ -* black_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* white_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* process_detail: ´˴¦ÉèΪFalse½«Ìø¹ý±ßԵ´¦ÀíÒԽÚʡÔËÐÐʱ¼䡣 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘黑色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 ### PersonMaskUltra -ΪÈËÎïÉú³ÉÁ³¡¢ͷ·¢¡¢ÉíÌåƤ·ô¡¢Ò·þ»òÅäÊεÄÕÚÕ֡£Óë֮ǰµÄA Person Mask Generator½ڵãÏà±ȣ¬Õâ¸ö½ڵã¾ßÓг¬¸ߵıßԵϸ½ڡ£ -±¾½ڵãµÄģÐʹúÂëÀ´×Ô[a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator)£¬±ßԵ´¦Àí´úÂëÀ´×ÔspacepxlµÄ[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)¡£ +为人物生成脸、头发、身体皮肤、衣服或配饰的遮罩。与之前的A Person Mask Generator节点相比,这个节点具有超高的边缘细节。 +本节点的模型代码来自[a-person-mask-generator](https://github.com/djbielejeski/a-person-mask-generator),边缘处理代码来自spacepxl的[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)。 ![image](image/person_mask_ultra_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/person_mask_ultra_node.png) -* face: Á³²¿ʶ±ð¡£ -* hair: ͷ·¢ʶ±ð¡£ -* body: ÉíÌåƤ·ôʶ±ð¡£ -* clothes: Ò·þʶ±ð¡£ -* accessories: ÅäÊÎ(ÀýÈ米°ü)ʶ±ð¡£ -* background: ±³¾°ʶ±ð¡£ -* confidence: ʶ±ðãÐֵ£¬¸üµ͵Äֵ½«Êä³ö¸ü¶àµÄÕÚÕַ¶Χ¡£ -* detail_range: ±ßԵϸ½ڷ¶Χ¡£ -* black_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* white_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* process_detail: ´˴¦ÉèΪFalse½«Ìø¹ý±ßԵ´¦ÀíÒԽÚʡÔËÐÐʱ¼䡣 +* face: 脸部识别。 +* hair: 头发识别。 +* body: 身体皮肤识别。 +* clothes: 衣服识别。 +* accessories: 配饰(例如背包)识别。 +* background: 背景识别。 +* confidence: 识别阈值,更低的值将输出更多的遮罩范围。 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘黑色采样阈值。 +* process_detail: 此处设为False将跳过边缘处理以节省运行时间。 ### PixelSpread -¶ÔͼÏñµÄÕÚÕֱßԵ²¿·ֽøÐÐÏñËØÀ©ÕÅԤ´¦Àí£¬¿ÉÓÐЧ¸ÄÉÆͼÏñºϳɵıßԵ¡£ +对图像的遮罩边缘部分进行像素扩张预处理,可有效改善图像合成的边缘。 ![image](image/pixel_spread_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/pixel_spread_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* mask_grow: ÕÚÕÖÀ©Õŷù¶ȡ£ +* invert_mask: 是否反转遮罩。 +* mask_grow: 遮罩扩张幅度。 ### MaskByDifferent -¼ÆËãÁ½ÕÅͼÏñ²»֮ͬ´¦£¬²¢Êä³öΪÕÚÕ֡£ +计算两张图像不同之处,并输出为遮罩。 ![image](image/mask_by_different_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_by_different_node.png) -* gain: ¼ÆËãÔöÒ档µ÷¸ߴËֵ£¬΢ÈõµIJîÒ콫¸üÏÔÖøµijÊÏ֡£ -* fix_gap: Ð޲¹ÕÚÕÖÄڲ¿·ì϶¡£¸ü¸ߵÄֵ½«Ð޲¹¸ü´óµķì϶¡£ -* fix_threshold: Ð޲¹ãÐֵ¡£ -* main_subject_detect: ´ËÏîÉèΪTrue½«¿ªÆôÖ÷ÌåÕì²⣬ºöÂÔÖ÷Ìå֮ÍâµIJîÒ졣 +* gain: 计算增益。调高此值,微弱的差异将更显著的呈现。 +* fix_gap: 修补遮罩内部缝隙。更高的值将修补更大的缝隙。 +* fix_threshold: 修补阈值。 +* main_subject_detect: 此项设为True将开启主体侦测,忽略主体之外的差异。 ### MaskEdgeUltraDetail -´¦Àí½ϴֲڵÄÕÚÕÖʹÆä»ñµó¬¾«ϸ±ßԵ¡£ -±¾½ڵã½áºÏÁËspacepxlµÄ[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)µÄAlpha MatteºÍGuided Filter AlphaÁ½Õ߹¦Äܡ£ +处理较粗糙的遮罩使其获得超精细边缘。 +本节点结合了spacepxl的[ComfyUI-Image-Filters](https://github.com/spacepxl/ComfyUI-Image-Filters)的Alpha Matte和Guided Filter Alpha两者功能。 ![image](image/mask_edge_ultra_detail_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_edge_ultra_detail_node.png) -* method: ÌṩPyMattingºÍOpenCV-GuidedFilterÁ½Öַ½·¨´¦Àí±ßԵ¡£PyMatting´¦ÀíËٶȽÏÂý£¬µ«ÊǶÔÓÚÊÓƵ£¬½¨ÒéʹÓÃÕâÖַ½·¨»ñµøüƽ»¬µÄÕÚÕÖÐòÁС£ -* mask_grow: ÕÚÕÖÀ©Õŷù¶ȡ£ÕýֵÊÇÏòÍâÀ©Õţ¬¸ºֵÊÇÏòÄÚÊÕËõ¡£¶ÔÓڽϴֲڵÄÕÚÕ֣¬ͨ³£ʹÓøºֵʹÆä±ßԵÊÕËõÒԻñµøüºõÄЧ¹û¡£ -* fix_gap: Ð޲¹ÕÚÕÖÖеĿÕ϶¡£Èç¹ûÕÚÕÖÖÐÓбȽÏÃ÷ÏԵĿÕ϶£¬Êʵ±µ÷¸ߴËÊýֵ¡£ -* fix_threshold: Ð޲¹ÕÚÕֵÄãÐֵ¡£ -* detail_range: ±ßԵϸ½ڷ¶Χ¡£ -* black_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ -* white_point: ±ßԵºÚɫ²ÉÑùãÐֵ¡£ +* method: 提供PyMatting和OpenCV-GuidedFilter两种方法处理边缘。PyMatting处理速度较慢,但是对于视频,建议使用这种方法获得更平滑的遮罩序列。 +* mask_grow: 遮罩扩张幅度。正值是向外扩张,负值是向内收缩。对于较粗糙的遮罩,通常使用负值使其边缘收缩以获得更好的效果。 +* fix_gap: 修补遮罩中的空隙。如果遮罩中有比较明显的空隙,适当调高此数值。 +* fix_threshold: 修补遮罩的阈值。 +* detail_range: 边缘细节范围。 +* black_point: 边缘黑色采样阈值。 +* white_point: 边缘黑色采样阈值。 ### MaskGrow -¶Ômask½øÐÐÀ©ÕÅÊÕËõ±ßԵºÍģºý´¦Àí +对mask进行扩张收缩边缘和模糊处理 ![image](image/mask_grow_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_grow_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* grow: À©Õŷù¶ȡ£ÕýֵÊÇÏòÍâÀ©Õţ¬¸ºֵÊÇÏòÄÚÊÕËõ¡£ -* blur: ģºý¡£ +* invert_mask: 是否反转遮罩。 +* grow: 扩张幅度。正值是向外扩张,负值是向内收缩。 +* blur: 模糊。 ### MaskEdgeShrink -ʹmask±ßԵƽ»¬µعý¶ÉÊÕËõ£¬²¢±£Áô±ßԵϸ½ڡ£ +使mask边缘平滑地过渡收缩,并保留边缘细节。 ![image](image/mask_edge_shrink_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_edge_shrink_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* shrink_level: ÊÕËõƽ»¬¼¶±ð¡£ -* soft: ƽ»¬·ù¶ȡ£ -* edge_shrink: ±ßԵÊÕËõ·ù¶ȡ£ -* edge_reserve: ±£Áô±ßԵϸ½ڷù¶È, 100ΪÍêȫ±£Áô£¬0ΪÍêȫ²»±£Áô¡£ +* invert_mask: 是否反转遮罩。 +* shrink_level: 收缩平滑级别。 +* soft: 平滑幅度。 +* edge_shrink: 边缘收缩幅度。 +* edge_reserve: 保留边缘细节幅度, 100为完全保留,0为完全不保留。 -MaskGrowÓëMaskEdgeShrinkЧ¹û¶ԱÈ +MaskGrow与MaskEdgeShrink效果对比 ![image](image/mask_edge_compare.png) ### MaskMotionBlur -ʹmask²úÉúÔ˶¯ģºý¡£ +使mask产生运动模糊。 ![image](image/mask_motion_blur_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_motion_blur_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* blur: ģºý´óС¡£ -* angle: ģºý½Ƕȡ£ +* invert_mask: 是否反转遮罩。 +* blur: 模糊大小。 +* angle: 模糊角度。 ### MaskGradient -ʹmask´Óһ²à²úÉú½¥±䡣ÇëעÒâ´˽ڵãÓëCreateGradientMaskµÄÇø±ð¡£ +使mask从一侧产生渐变。请注意此节点与CreateGradientMask的区别。 ![image](image/mask_gradient_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_gradient_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* gradient_side: ´ÓÄĸö±߲úÉú½¥±䡣ÓÐËĸö·½Ï򣺶¥²àtop¡¢µײàbottom¡¢×ó²àleft¡¢ÓҲàright¡£ -* gradient_scale: ½¥±ä¾àÀ롣ĬÈÏֵ100±íʾ½¥±ä²úÉúһ²àÍêȫ͸Ã÷£¬Áíһ²àÍêȫ²»͸Ã÷¡£ÊýֵԽС£¬´Ó͸Ã÷µ½²»͸Ã÷µľàÀëԽ¶̡£ -* gradient_offset: ½¥±äλÖÃƫÒơ£ -* opacity: ½¥±äµIJ»͸Ã÷¶ȡ£ +* invert_mask: 是否反转遮罩。 +* gradient_side: 从哪个边产生渐变。有四个方向:顶侧top、底侧bottom、左侧left、右侧right。 +* gradient_scale: 渐变距离。默认值100表示渐变产生一侧完全透明,另一侧完全不透明。数值越小,从透明到不透明的距离越短。 +* gradient_offset: 渐变位置偏移。 +* opacity: 渐变的不透明度。 ### CreateGradientMask -´´½¨һ¸ö½¥±äµÄÕÚÕ֡£ÇëעÒâ´˽ڵãÓëMaskGradientµÄÇø±ð¡£ +创建一个渐变的遮罩。请注意此节点与MaskGradient的区别。 ![image](image/create_gradient_mask_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/create_gradient_mask_node.png) -* size_as*: ´˴¦ÊäÈëͼÏñ»òÕÚÕ֣¬½«°´ÕÕÆä³ߴçÉú³ÉÊä³öͼÏñºÍÕÚÕ֡£עÒ⣬´ËÊäÈëÓÅÏȼ¶¸ßÓÚÏÂÃæµÄwidthºÍheight¡£ -* width: »­ÃæµĿí¶ȡ£Èç¹ûÓÐsize_asÊäÈ룬´ËÉèÖý«±»ºöÂԡ£ -* height: »­Ãæµĸ߶ȡ£Èç¹ûÓÐsize_asÊäÈ룬´ËÉèÖý«±»ºöÂԡ£ -* gradient_side: ´ÓÄĸö±߲úÉú½¥±䡣ÓÐËĸö·½Ï򣺶¥²àtop¡¢µײàbottom¡¢×ó²àleft¡¢ÓҲàright¡£ -* gradient_scale: ½¥±ä¾àÀ롣ĬÈÏֵ100±íʾ½¥±ä²úÉúһ²àÍêȫ͸Ã÷£¬Áíһ²àÍêȫ²»͸Ã÷¡£ÊýֵԽС£¬´Ó͸Ã÷µ½²»͸Ã÷µľàÀëԽ¶̡£ -* gradient_offset: ½¥±äλÖÃƫÒơ£ -* opacity: ½¥±äµIJ»͸Ã÷¶ȡ£ +* size_as*: 此处输入图像或遮罩,将按照其尺寸生成输出图像和遮罩。注意,此输入优先级高于下面的width和height。 +* width: 画面的宽度。如果有size_as输入,此设置将被忽略。 +* height: 画面的高度。如果有size_as输入,此设置将被忽略。 +* gradient_side: 从哪个边产生渐变。有四个方向:顶侧top、底侧bottom、左侧left、右侧right。 +* gradient_scale: 渐变距离。默认值100表示渐变产生一侧完全透明,另一侧完全不透明。数值越小,从透明到不透明的距离越短。 +* gradient_offset: 渐变位置偏移。 +* opacity: 渐变的不透明度。 -*½öÏÞÊäÈëimageºÍmask, Èç¹ûǿÖƽÓÈëÆäËûÀàÐÍÊäÈ룬½«µ¼Ö½ڵã´íÎó¡£ +*仅限输入image和mask, 如果强制接入其他类型输入,将导致节点错误。 ### MaskStroke -²úÉúmaskÂÖÀªÃè±ߡ£ +产生mask轮廓描边。 ![image](image/mask_stroke_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/mask_stroke_node.png) -* invert_mask: ÊǷñ·´תÕÚÕ֡£ -* stroke_grow: Ãè±ßÀ©ÕÅ/ÊÕËõ·ù¶ȣ¬ÕýֵÊÇÀ©Õţ¬¸ºֵÊÇÊÕËõ¡£ -* stroke_width: Ãè±߿í¶ȡ£ -* blur: Ãè±ßģºý¡£ +* invert_mask: 是否反转遮罩。 +* stroke_grow: 描边扩张/收缩幅度,正值是扩张,负值是收缩。 +* stroke_width: 描边宽度。 +* blur: 描边模糊。 ### MaskPreview -ԤÀÀmask +预览mask ![image](image/mask_invert.png) ### MaskInvert -mask·´ת +mask反转 ![image](image/mask_invert_node.png) @@ -885,134 +938,122 @@ mask ![image](image/layerfilter_nodes.png) ### Sharp & Soft -ΪͼÏñÔöǿϸ½ڻòĨƽϸ½ڡ£ +为图像增强细节或抹平细节。 ![image](image/sharp_and_soft_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/sharp_and_soft_node.png) -* enhance: ÌṩËĸöԤÉ赵룬·ֱðÊÇvery sharp¡¢sharp¡¢softºÍvery soft¡£ +* enhance: 提供四个预设档位,分别是very sharp、sharp、soft和very soft。 ### SkinBeauty -ĥƤЧ¹û¡£ +磨皮效果。 ![image](image/skin_beauty_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/skin_beauty_node.png) -* smooth: Ƥ·ôƽ»¬¶ȡ£ -* threshold: ĥƤ·¶Χ¡£ÊýֵԽС·¶ΧԽ´ó¡£ -* opacity: ĥƤµIJ»͸Ã÷¶ȡ£ +* smooth: 皮肤平滑度。 +* threshold: 磨皮范围。数值越小范围越大。 +* opacity: 磨皮的不透明度。 ### WaterColor -ˮ²ʻ­Ч¹û¡£ +水彩画效果。 ![image](image/water_color_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/water_color_node.png) -* line_density: ÏßÌõÃܶȡ£ -* opacity: ˮ²ÊЧ¹ûµIJ»͸Ã÷¶ȡ£ +* line_density: 线条密度。 +* opacity: 水彩效果的不透明度。 ### SoftLight -Èá¹âЧ¹û¡£ +柔光效果。 ![image](image/soft_light_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/soft_light_node.png) -* soft: Èá¹â´óС¡£ -* threshold: Èá¹ⷶΧ¡£Èá¹â´ӻ­Ãæ×îÃ÷ÁÁµIJ¿·ֳÊÏ֡£ÊýֵԽµͷ¶ΧԽ´ó£¬Խ¸߷¶ΧԽС¡£ -* opacity: Èá¹âµIJ»͸Ã÷¶ȡ£ +* soft: 柔光大小。 +* threshold: 柔光范围。柔光从画面最明亮的部分呈现。数值越低范围越大,越高范围越小。 +* opacity: 柔光的不透明度。 ### ChannelShake -ͨµÀ´íλ¡£ÀàËƶ¶ÒôlogoµÄЧ¹û¡£ +通道错位。类似抖音logo的效果。 ![image](image/channel_shake_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/channel_shake_node.png) -* distance: ͨµÀ·ÖÀ뵾àÀ롣 -* angle: ͨµÀ·ÖÀ뵼Ƕȡ£ -* mode: ͨµÀ´íλÅÅÁÐ˳Ðò¡£ +* distance: 通道分离的距离。 +* angle: 通道分离的角度。 +* mode: 通道错位排列顺序。 ### Film -ģÄ⽺ƬµĿÅÁ£¡¢°µ±ߺͱßԵģºý£¬֧³ÖÊäÈëÉî¶ÈͼģÄâÐ齹¡£ -Õâ¸ö½ڵãÊÇ[digitaljohn/comfyui-propost](https://github.com/digitaljohn/comfyui-propost)µÄÖØÐ·âװ¡£ +模拟胶片的颗粒、暗边和边缘模糊,支持输入深度图模拟虚焦。 +这个节点是[digitaljohn/comfyui-propost](https://github.com/digitaljohn/comfyui-propost)的重新封装。 ![image](image/film_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/film_node.png) -* image: ÊäÈëµÄͼƬ¡£ -* depth_map: Éî¶ÈͼÊäÈ룬ÓɴËģÄâÐ齹Ч¹û¡£´ËÏîÊǿÉѡÊäÈ룬Èç¹ûûÓÐÊäÈëÔòģÄâΪͼƬ±ßԵµľ¶Ïòģºý¡£ -* center_x: °µ±ߺ;¶ÏòģºýµÄÖÐÐĵãλÖúá×ø±꣬0±íʾ×î×ó²࣬1±íʾ×îÓҲ࣬0.5±íʾÔÚÖÐÐġ£ -* center_y: °µ±ߺ;¶ÏòģºýµÄÖÐÐĵãλÖÃ×Ý×ø±꣬0±íʾ×îÉϷ½£¬1±íʾ×îÏ·½£¬0.5±íʾÔÚÖÐÐġ£ -* saturation: ÑÕɫ±¥ºͶȣ¬1Ϊԭʼֵ¡£ -* grain_power: Ôëµãǿ¶ȡ£ÊýֵԽ´ó£¬ÔëµãԽÃ÷Ïԡ£ -* grain_scale: Ôëµã¿ÅÁ£´óС¡£ÊýֵԽ´󣬿ÅÁ£Խ´ó¡£ -* grain_sat: ÔëµãµÄɫ²ʱ¥ºͶȡ£0±íʾºڰ×Ôëµ㣬ÊýֵԽ´󣬲ÊɫԽÃ÷Ïԡ£ -* grain_shadows: °µ²¿Ôëµãǿ¶ȡ£ -* grain_highs: ÁÁ²¿Ôëµãǿ¶ȡ£ -* blur_strength: ģºýǿ¶ȡ£ÊýֵԽ´óԽģºý¡£ -* blur_focus_spread: ½¹µãÀ©ɢ·¶Χ¡£ÊýֵԽ´ó£¬ÇåÎúµķ¶ΧԽ´ó¡£ -* focal_depth: ģÄâÐ齹µĽ¹µã¾àÀ롣0±íʾ½¹µãÔÚ×îԶ£¬1±íʾ½¹µãÔÚ×î½ü¡£´ËÏîÉèÖÃֻÔÚdepth_mapÓÐÊäÈëʱ²ÅÉúЧ¡£ +* image: 输入的图片。 +* depth_map: 深度图输入,由此模拟虚焦效果。此项是可选输入,如果没有输入则模拟为图片边缘的径向模糊。 +* center_x: 暗边和径向模糊的中心点位置横坐标,0表示最左侧,1表示最右侧,0.5表示在中心。 +* center_y: 暗边和径向模糊的中心点位置纵坐标,0表示最上方,1表示最下方,0.5表示在中心。 +* saturation: 颜色饱和度,1为原始值。 +* grain_power: 噪点强度。数值越大,噪点越明显。 +* grain_scale: 噪点颗粒大小。数值越大,颗粒越大。 +* grain_sat: 噪点的色彩饱和度。0表示黑白噪点,数值越大,彩色越明显。 +* grain_shadows: 暗部噪点强度。 +* grain_highs: 亮部噪点强度。 +* blur_strength: 模糊强度。数值越大越模糊。 +* blur_focus_spread: 焦点扩散范围。数值越大,清晰的范围越大。 +* focal_depth: 模拟虚焦的焦点距离。0表示焦点在最远,1表示焦点在最近。此项设置只在depth_map有输入时才生效。 ### LightLeak -ģÄ⽺Ƭ©¹âЧ¹û¡£ÇëÏÂÔØ[light_leak.pkl(°ٶÈÍøÅÌ)](https://pan.baidu.com/s/1QY1ZyYm885krrqDB2t8lPg?pwd=yvs3)»ò[light_leak.pkl(Google Drive)(https://drive.google.com/file/d/1DcH2Zkyj7W3OiAeeGpJk1eaZpdJwdCL-/view?usp=sharing)½«Îļþ¸´ÖƵ½```ComfyUI/models/layerstyle``` Îļþ¼С£ +模拟胶片漏光效果。请下载[light_leak.pkl(百度网盘)](https://pan.baidu.com/s/1QY1ZyYm885krrqDB2t8lPg?pwd=yvs3)或[light_leak.pkl(Google Drive)(https://drive.google.com/file/d/1DcH2Zkyj7W3OiAeeGpJk1eaZpdJwdCL-/view?usp=sharing)将文件复制到```ComfyUI/models/layerstyle``` 文件夹。 ![image](image/light_leak_example.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/light_leak_node.png) -* light: ÌṩÁË32Öֹâ°ߡ£randomΪËæ»úѡÔñ¡£ -* corner: ¹â°߳öÏֵĽÇÂ䣬ÓÐ×óÉϡ¢ÓÒÉϡ¢×óϺÍÓÒÏÂ4¸öѡÏ -* hue: ¹â°ߵÄɫÏࡣ -* saturation: ¹â°ߵÄɫ²ʱ¥ºͶȡ£ -* opacity: ¹â°ߵIJ»͸Ã÷¶ȡ£ +* light: 提供了32种光斑。random为随机选择。 +* corner: 光斑出现的角落,有左上、右上、左下和右下4个选项。 +* hue: 光斑的色相。 +* saturation: 光斑的色彩饱和度。 +* opacity: 光斑的不透明度。 ### ColorMap -α²ÊɫÈÈÁ¦ͼЧ¹û¡£ +伪彩色热力图效果。 ![image](image/colormap_result.png) -½ڵãѡÏî˵Ã÷: +节点选项说明: ![image](image/color_map_node.png) -* color_map: Ч¹ûÀàÐ͡£¹²22Ö֣¬¸÷ÖÖÀàÐ͵ÄЧ¹ûÈçÉÏͼËùʾ¡£ -* opacity: α²ÊɫЧ¹ûµIJ»͸Ã÷¶ȡ£ +* color_map: 效果类型。共22种,各种类型的效果如上图所示。 +* opacity: 伪彩色效果的不透明度。 ### MotionBlur -Ô˶¯ģºý¡£ +运动模糊。 ![image](image/motion_blur_example.png) -½ڵãѡÏî˵Ã÷: -* angle: ģºý½Ƕȡ£ -* blur: ģºý´óС¡£ +节点选项说明: +* angle: 模糊角度。 +* blur: 模糊大小。 ### GaussianBlur -¸ß˹ģºý¡£ +高斯模糊。 ![image](image/gaussian_blur_example.png) -½ڵãѡÏî˵Ã÷: -* blur: ģºý´óС¡£ +节点选项说明: +* blur: 模糊大小。 -## ½ڵãע½â -1 image¡¢maskºÍbackground_image(Èç¹ûÓÐÊäÈë)ÕâÈýÏî±ØÐëÊÇÏàͬµijߴ硣 -2 mask²»ÊDZØÐëµÄÊäÈëÏĬÈÏʹÓÃimageµÄalphaͨµÀ£¬Èç¹ûimageÊäÈ벻°üº¬alphaͨµÀ½«×Զ¯´´½¨Õû¸öͼÏñµÄalphaͨµÀ¡£Èç¹ûÊäÈëmask£¬ԭ±¾µÄalphaͨµÀ½«±»mask¸²¸ǡ£ -3 »ìºÏģʽ°üÀ¨normal¡¢multply¡¢screen¡¢add¡¢subtract¡¢difference¡¢darker¡¢lighter¡¢color_burn¡¢color_dodge¡¢linear_burn¡¢linear_dodge¡¢overlay¡¢soft_light¡¢hard_light¡¢vivid_light¡¢pin_light¡¢linear_light¡¢hard_mix, ¹²19ÖֻìºÏģʽ +## 节点注解 +1 image、mask和background_image(如果有输入)这三项必须是相同的尺寸。 +2 mask不是必须的输入项,默认使用image的alpha通道,如果image输入不包含alpha通道将自动创建整个图像的alpha通道。如果输入mask,原本的alpha通道将被mask覆盖。 +3 混合模式包括normal、multply、screen、add、subtract、difference、darker、lighter、color_burn、color_dodge、linear_burn、linear_dodge、overlay、soft_light、hard_light、vivid_light、pin_light、linear_light、hard_mix, 共19种混合模式 ![image](image/blend_mode_result.png) -*»ìºÏģʽԤÀÀ
+*混合模式预览
-4 ÑÕɫʹÓÃ16½øÖÆRGB×ַû´®¸ñʽÃèÊö£¬ÀýÈç '#FA3D86'¡£ -5 imageºÍmaskÕâÁ½Ïî±ØÐëÊÇÏàͬµijߴ硣 - -## ʹÓÃʾÀý - -ÔÚworkflowĿ¼ÏÂÓÐjson¸ñʽµĹ¤×÷Á÷ʾÀýÎļþ¡£ +4 颜色使用16进制RGB字符串格式描述,例如 '#FA3D86'。 +5 image和mask这两项必须是相同的尺寸。 -## °²װ·½·¨ - -* ÍƼöʹÓà ComfyUI Manager °²װ¡£ -* »òÕßÔÚCompyUI²å¼þĿ¼(ÀýÈ硰CompyUI\custom_nodes\¡±)Öдò¿ªcmd´°¿ڣ¬¼üÈë```git clone https://github.com/chflame163/ComfyUI_LayerStyle.git```°²װ¡£»òÕßÏÂÔؽâѹzipÎļþ£¬½«µõ½µÄÎļþ¼и´ÖƵ½ ComfyUI\custom_nodes\ - - °²װÒÀÀµ°ü£¬ÔÚ×ÊԴ¹ÜÀíÆ÷ComfyUI\custom_nodes\ComfyUI_LayerStyle ²å¼þĿ¼λÖôò¿ªcmd´°¿ڣ¬ÊäÈëÒÔÏÂÃüÁ - - ```..\..\..\python_embeded\python.exe -m pip install -r requirements.txt``` - - ÖØÐ´ò¿ªComfyUI¡£ +## 声明 +LayerStyle节点遵照MIT开源协议,有部分功能代码来自其他开源项目。如果作为商业用途,请查阅原项目授权协议使用。 diff --git a/image/lama_example.png b/image/lama_example.png new file mode 100644 index 0000000..3cc11c3 Binary files /dev/null and b/image/lama_example.png differ diff --git a/image/lama_node.png b/image/lama_node.png new file mode 100644 index 0000000..1264140 Binary files /dev/null and b/image/lama_node.png differ diff --git a/image/layerfilter_nodes.png b/image/layerfilter_nodes.png index 6dd7f84..51d9240 100644 Binary files a/image/layerfilter_nodes.png and b/image/layerfilter_nodes.png differ diff --git a/image/layermask_nodes.png b/image/layermask_nodes.png index 3a7c102..335386e 100644 Binary files a/image/layermask_nodes.png and b/image/layermask_nodes.png differ diff --git a/image/layerutility_nodes.png b/image/layerutility_nodes.png index 5ab66e0..54c4dce 100644 Binary files a/image/layerutility_nodes.png and b/image/layerutility_nodes.png differ diff --git a/image/menu_layer_color.png b/image/menu_layer_color.png new file mode 100644 index 0000000..254dc6f Binary files /dev/null and b/image/menu_layer_color.png differ diff --git a/image/menu_layer_filter.png b/image/menu_layer_filter.png new file mode 100644 index 0000000..a002271 Binary files /dev/null and b/image/menu_layer_filter.png differ diff --git a/image/menu_layer_mask.png b/image/menu_layer_mask.png new file mode 100644 index 0000000..90bc5f6 Binary files /dev/null and b/image/menu_layer_mask.png differ diff --git a/image/menu_layer_style.png b/image/menu_layer_style.png new file mode 100644 index 0000000..54cfbc8 Binary files /dev/null and b/image/menu_layer_style.png differ diff --git a/image/menu_layer_utility.png b/image/menu_layer_utility.png new file mode 100644 index 0000000..b5aa3ea Binary files /dev/null and b/image/menu_layer_utility.png differ diff --git a/image/node-menu.png b/image/node-menu.png new file mode 100644 index 0000000..4962e17 Binary files /dev/null and b/image/node-menu.png differ diff --git a/image/node-search.png b/image/node-search.png new file mode 100644 index 0000000..1e993c2 Binary files /dev/null and b/image/node-search.png differ diff --git a/py/imagefunc.py b/py/imagefunc.py index 6c78603..58585eb 100644 --- a/py/imagefunc.py +++ b/py/imagefunc.py @@ -25,7 +25,7 @@ import torch.nn.functional as F import colorsys from colour.io.luts.iridas_cube import read_LUT_IridasCube, LUT3D, LUT3x1D from typing import Union -import folder_paths as COMFY_FOLDER_PATH +import folder_paths from .briarmbg import BriaRMBG from .filmgrainer import processing as processing_utils from .filmgrainer import filmgrainer as filmgrainer @@ -70,7 +70,7 @@ def load_pickle(file_name:str) -> object: return obj def load_light_leak_images() -> list: - file = os.path.join(COMFY_FOLDER_PATH.models_dir, "layerstyle", "light_leak.pkl") + file = os.path.join(folder_paths.models_dir, "layerstyle", "light_leak.pkl") return load_pickle(file) '''Converter''' @@ -847,11 +847,11 @@ def load_RMBG_model(): net = BriaRMBG() model_path = "" try: - model_path = os.path.join(os.path.normpath(COMFY_FOLDER_PATH.folder_names_and_paths['rmbg'][0][0]), "model.pth") + model_path = os.path.join(os.path.normpath(folder_paths.folder_names_and_paths['rmbg'][0][0]), "model.pth") except: pass if not os.path.exists(model_path): - model_path = os.path.join(COMFY_FOLDER_PATH.models_dir, "rmbg", "RMBG-1.4", "model.pth") + model_path = os.path.join(folder_paths.models_dir, "rmbg", "RMBG-1.4", "model.pth") if not os.path.exists(model_path): model_path = os.path.join(os.path.dirname(current_directory), "RMBG-1.4", "model.pth") net.load_state_dict(torch.load(model_path, map_location=device)) @@ -1131,6 +1131,27 @@ def calculate_side_by_ratio(orig_width:int, orig_height:int, ratio:float, longes target_width = int(target_width * _r) return target_width, target_height + +def generate_random_name(prefix:str, suffix:str, length:int) -> str: + name = ''.join(random.choice("abcdefghijklmnopqrstupvxyz1234567890") for x in range(length)) + return prefix + name + suffix + +def check_image_file(file_name:str, interval:int) -> object: + while True: + if os.path.isfile(file_name): + try: + image = Image.open(file_name) + ret_image = copy.deepcopy(image) + image.close() + return ret_image + except Exception as e: + print(e) + return None + break + time.sleep(interval / 1000) + + + '''CLASS''' class AnyType(str): diff --git a/py/iopaint/__init__.py b/py/iopaint/__init__.py new file mode 100644 index 0000000..852736e --- /dev/null +++ b/py/iopaint/__init__.py @@ -0,0 +1,23 @@ +import os + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +# https://github.com/pytorch/pytorch/issues/27971#issuecomment-1768868068 +os.environ["ONEDNN_PRIMITIVE_CACHE_CAPACITY"] = "1" +os.environ["LRU_CACHE_CAPACITY"] = "1" +# prevent CPU memory leak when run model on GPU +# https://github.com/pytorch/pytorch/issues/98688#issuecomment-1869288431 +# https://github.com/pytorch/pytorch/issues/108334#issuecomment-1752763633 +os.environ["TORCH_CUDNN_V8_API_LRU_CACHE_LIMIT"] = "1" + + +import warnings + +warnings.simplefilter("ignore", UserWarning) + + +def entry_point(): + # To make os.environ["XDG_CACHE_HOME"] = args.model_cache_dir works for diffusers + # https://github.com/huggingface/diffusers/blob/be99201a567c1ccd841dc16fb24e88f7f239c187/src/diffusers/utils/constants.py#L18 + from .cli import typer_app + + typer_app() diff --git a/py/iopaint/__main__.py b/py/iopaint/__main__.py new file mode 100644 index 0000000..73b4ed7 --- /dev/null +++ b/py/iopaint/__main__.py @@ -0,0 +1,4 @@ +from . import entry_point + +if __name__ == "__main__": + entry_point() diff --git a/py/iopaint/api.py b/py/iopaint/api.py new file mode 100644 index 0000000..d98574f --- /dev/null +++ b/py/iopaint/api.py @@ -0,0 +1,397 @@ +import asyncio +import os +import threading +import time +import traceback +from pathlib import Path +from typing import Optional, Dict, List + +import cv2 +import numpy as np +import socketio +import torch + +try: + torch._C._jit_override_can_fuse_on_cpu(False) + torch._C._jit_override_can_fuse_on_gpu(False) + torch._C._jit_set_texpr_fuser_enabled(False) + torch._C._jit_set_nvfuser_enabled(False) +except: + pass + + +import uvicorn +from PIL import Image +from fastapi import APIRouter, FastAPI, Request, UploadFile +from fastapi.encoders import jsonable_encoder +from fastapi.exceptions import HTTPException +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import JSONResponse, FileResponse, Response +from fastapi.staticfiles import StaticFiles +from loguru import logger +from socketio import AsyncServer + +from .file_manager import FileManager +from .helper import ( + load_img, + decode_base64_to_image, + pil_to_bytes, + numpy_to_bytes, + concat_alpha_channel, + gen_frontend_mask, + adjust_mask, +) +from .model.utils import torch_gc +from .model_manager import ModelManager +from .plugins import build_plugins, RealESRGANUpscaler, InteractiveSeg +from .plugins.base_plugin import BasePlugin +from .plugins.remove_bg import RemoveBG +from .schema import ( + GenInfoResponse, + ApiConfig, + ServerConfigResponse, + SwitchModelRequest, + InpaintRequest, + RunPluginRequest, + SDSampler, + PluginInfo, + AdjustMaskRequest, + RemoveBGModel, + SwitchPluginModelRequest, + ModelInfo, + InteractiveSegModel, + RealESRGANModel, +) + +CURRENT_DIR = Path(__file__).parent.absolute().resolve() +WEB_APP_DIR = CURRENT_DIR / "web_app" + + +def api_middleware(app: FastAPI): + rich_available = False + try: + if os.environ.get("WEBUI_RICH_EXCEPTIONS", None) is not None: + import anyio # importing just so it can be placed on silent list + import starlette # importing just so it can be placed on silent list + from rich.console import Console + + console = Console() + rich_available = True + except Exception: + pass + + def handle_exception(request: Request, e: Exception): + err = { + "error": type(e).__name__, + "detail": vars(e).get("detail", ""), + "body": vars(e).get("body", ""), + "errors": str(e), + } + if not isinstance( + e, HTTPException + ): # do not print backtrace on known httpexceptions + message = f"API error: {request.method}: {request.url} {err}" + if rich_available: + print(message) + console.print_exception( + show_locals=True, + max_frames=2, + extra_lines=1, + suppress=[anyio, starlette], + word_wrap=False, + width=min([console.width, 200]), + ) + else: + traceback.print_exc() + return JSONResponse( + status_code=vars(e).get("status_code", 500), content=jsonable_encoder(err) + ) + + @app.middleware("http") + async def exception_handling(request: Request, call_next): + try: + return await call_next(request) + except Exception as e: + return handle_exception(request, e) + + @app.exception_handler(Exception) + async def fastapi_exception_handler(request: Request, e: Exception): + return handle_exception(request, e) + + @app.exception_handler(HTTPException) + async def http_exception_handler(request: Request, e: HTTPException): + return handle_exception(request, e) + + cors_options = { + "allow_methods": ["*"], + "allow_headers": ["*"], + "allow_origins": ["*"], + "allow_credentials": True, + "expose_headers": ["X-Seed"] + } + app.add_middleware(CORSMiddleware, **cors_options) + + +global_sio: AsyncServer = None + + +def diffuser_callback(pipe, step: int, timestep: int, callback_kwargs: Dict = {}): + # self: DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict + # logger.info(f"diffusion callback: step={step}, timestep={timestep}") + + # We use asyncio loos for task processing. Perhaps in the future, we can add a processing queue similar to InvokeAI, + # but for now let's just start a separate event loop. It shouldn't make a difference for single person use + asyncio.run(global_sio.emit("diffusion_progress", {"step": step})) + return {} + + +class Api: + def __init__(self, app: FastAPI, config: ApiConfig): + self.app = app + self.config = config + self.router = APIRouter() + self.queue_lock = threading.Lock() + api_middleware(self.app) + + self.file_manager = self._build_file_manager() + self.plugins = self._build_plugins() + self.model_manager = self._build_model_manager() + + # fmt: off + self.add_api_route("/api/v1/gen-info", self.api_geninfo, methods=["POST"], response_model=GenInfoResponse) + self.add_api_route("/api/v1/server-config", self.api_server_config, methods=["GET"], response_model=ServerConfigResponse) + self.add_api_route("/api/v1/model", self.api_current_model, methods=["GET"], response_model=ModelInfo) + self.add_api_route("/api/v1/model", self.api_switch_model, methods=["POST"], response_model=ModelInfo) + self.add_api_route("/api/v1/inputimage", self.api_input_image, methods=["GET"]) + self.add_api_route("/api/v1/inpaint", self.api_inpaint, methods=["POST"]) + self.add_api_route("/api/v1/switch_plugin_model", self.api_switch_plugin_model, methods=["POST"]) + self.add_api_route("/api/v1/run_plugin_gen_mask", self.api_run_plugin_gen_mask, methods=["POST"]) + self.add_api_route("/api/v1/run_plugin_gen_image", self.api_run_plugin_gen_image, methods=["POST"]) + self.add_api_route("/api/v1/samplers", self.api_samplers, methods=["GET"]) + self.add_api_route("/api/v1/adjust_mask", self.api_adjust_mask, methods=["POST"]) + self.add_api_route("/api/v1/save_image", self.api_save_image, methods=["POST"]) + self.app.mount("/", StaticFiles(directory=WEB_APP_DIR, html=True), name="assets") + # fmt: on + + global global_sio + self.sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins="*") + self.combined_asgi_app = socketio.ASGIApp(self.sio, self.app) + self.app.mount("/ws", self.combined_asgi_app) + global_sio = self.sio + + def add_api_route(self, path: str, endpoint, **kwargs): + return self.app.add_api_route(path, endpoint, **kwargs) + + def api_save_image(self, file: UploadFile): + filename = file.filename + origin_image_bytes = file.file.read() + with open(self.config.output_dir / filename, "wb") as fw: + fw.write(origin_image_bytes) + + def api_current_model(self) -> ModelInfo: + return self.model_manager.current_model + + def api_switch_model(self, req: SwitchModelRequest) -> ModelInfo: + if req.name == self.model_manager.name: + return self.model_manager.current_model + self.model_manager.switch(req.name) + return self.model_manager.current_model + + def api_switch_plugin_model(self, req: SwitchPluginModelRequest): + if req.plugin_name in self.plugins: + self.plugins[req.plugin_name].switch_model(req.model_name) + if req.plugin_name == RemoveBG.name: + self.config.remove_bg_model = req.model_name + if req.plugin_name == RealESRGANUpscaler.name: + self.config.realesrgan_model = req.model_name + if req.plugin_name == InteractiveSeg.name: + self.config.interactive_seg_model = req.model_name + torch_gc() + + def api_server_config(self) -> ServerConfigResponse: + plugins = [] + for it in self.plugins.values(): + plugins.append( + PluginInfo( + name=it.name, + support_gen_image=it.support_gen_image, + support_gen_mask=it.support_gen_mask, + ) + ) + + return ServerConfigResponse( + plugins=plugins, + modelInfos=self.model_manager.scan_models(), + removeBGModel=self.config.remove_bg_model, + removeBGModels=RemoveBGModel.values(), + realesrganModel=self.config.realesrgan_model, + realesrganModels=RealESRGANModel.values(), + interactiveSegModel=self.config.interactive_seg_model, + interactiveSegModels=InteractiveSegModel.values(), + enableFileManager=self.file_manager is not None, + enableAutoSaving=self.config.output_dir is not None, + enableControlnet=self.model_manager.enable_controlnet, + controlnetMethod=self.model_manager.controlnet_method, + disableModelSwitch=False, + isDesktop=False, + samplers=self.api_samplers(), + ) + + def api_input_image(self) -> FileResponse: + if self.config.input and self.config.input.is_file(): + return FileResponse(self.config.input) + raise HTTPException(status_code=404, detail="Input image not found") + + def api_geninfo(self, file: UploadFile) -> GenInfoResponse: + _, _, info = load_img(file.file.read(), return_info=True) + parts = info.get("parameters", "").split("Negative prompt: ") + prompt = parts[0].strip() + negative_prompt = "" + if len(parts) > 1: + negative_prompt = parts[1].split("\n")[0].strip() + return GenInfoResponse(prompt=prompt, negative_prompt=negative_prompt) + + def api_inpaint(self, req: InpaintRequest): + image, alpha_channel, infos = decode_base64_to_image(req.image) + mask, _, _ = decode_base64_to_image(req.mask, gray=True) + + mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)[1] + if image.shape[:2] != mask.shape[:2]: + raise HTTPException( + 400, + detail=f"Image size({image.shape[:2]}) and mask size({mask.shape[:2]}) not match.", + ) + + if req.paint_by_example_example_image: + paint_by_example_image, _, _ = decode_base64_to_image( + req.paint_by_example_example_image + ) + + start = time.time() + rgb_np_img = self.model_manager(image, mask, req) + logger.info(f"process time: {(time.time() - start) * 1000:.2f}ms") + torch_gc() + + rgb_np_img = cv2.cvtColor(rgb_np_img.astype(np.uint8), cv2.COLOR_BGR2RGB) + rgb_res = concat_alpha_channel(rgb_np_img, alpha_channel) + + ext = "png" + res_img_bytes = pil_to_bytes( + Image.fromarray(rgb_res), + ext=ext, + quality=self.config.quality, + infos=infos, + ) + + asyncio.run(self.sio.emit("diffusion_finish")) + + return Response( + content=res_img_bytes, + media_type=f"image/{ext}", + headers={"X-Seed": str(req.sd_seed)}, + ) + + def api_run_plugin_gen_image(self, req: RunPluginRequest): + ext = "png" + if req.name not in self.plugins: + raise HTTPException(status_code=422, detail="Plugin not found") + if not self.plugins[req.name].support_gen_image: + raise HTTPException( + status_code=422, detail="Plugin does not support output image" + ) + rgb_np_img, alpha_channel, infos = decode_base64_to_image(req.image) + bgr_or_rgba_np_img = self.plugins[req.name].gen_image(rgb_np_img, req) + torch_gc() + + if bgr_or_rgba_np_img.shape[2] == 4: + rgba_np_img = bgr_or_rgba_np_img + else: + rgba_np_img = cv2.cvtColor(bgr_or_rgba_np_img, cv2.COLOR_BGR2RGB) + rgba_np_img = concat_alpha_channel(rgba_np_img, alpha_channel) + + return Response( + content=pil_to_bytes( + Image.fromarray(rgba_np_img), + ext=ext, + quality=self.config.quality, + infos=infos, + ), + media_type=f"image/{ext}", + ) + + def api_run_plugin_gen_mask(self, req: RunPluginRequest): + if req.name not in self.plugins: + raise HTTPException(status_code=422, detail="Plugin not found") + if not self.plugins[req.name].support_gen_mask: + raise HTTPException( + status_code=422, detail="Plugin does not support output image" + ) + rgb_np_img, alpha_channel, infos = decode_base64_to_image(req.image) + bgr_or_gray_mask = self.plugins[req.name].gen_mask(rgb_np_img, req) + torch_gc() + res_mask = gen_frontend_mask(bgr_or_gray_mask) + return Response( + content=numpy_to_bytes(res_mask, "png"), + media_type="image/png", + ) + + def api_samplers(self) -> List[str]: + return [member.value for member in SDSampler.__members__.values()] + + def api_adjust_mask(self, req: AdjustMaskRequest): + mask, _, _ = decode_base64_to_image(req.mask, gray=True) + mask = adjust_mask(mask, req.kernel_size, req.operate) + return Response(content=numpy_to_bytes(mask, "png"), media_type="image/png") + + def launch(self): + self.app.include_router(self.router) + uvicorn.run( + self.combined_asgi_app, + host=self.config.host, + port=self.config.port, + timeout_keep_alive=999999999, + ) + + def _build_file_manager(self) -> Optional[FileManager]: + if self.config.input and self.config.input.is_dir(): + logger.info( + f"Input is directory, initialize file manager {self.config.input}" + ) + + return FileManager( + app=self.app, + input_dir=self.config.input, + output_dir=self.config.output_dir, + ) + return None + + def _build_plugins(self) -> Dict[str, BasePlugin]: + return build_plugins( + self.config.enable_interactive_seg, + self.config.interactive_seg_model, + self.config.interactive_seg_device, + self.config.enable_remove_bg, + self.config.remove_bg_model, + self.config.enable_anime_seg, + self.config.enable_realesrgan, + self.config.realesrgan_device, + self.config.realesrgan_model, + self.config.enable_gfpgan, + self.config.gfpgan_device, + self.config.enable_restoreformer, + self.config.restoreformer_device, + self.config.no_half, + ) + + def _build_model_manager(self): + return ModelManager( + name=self.config.model, + device=torch.device(self.config.device), + no_half=self.config.no_half, + low_mem=self.config.low_mem, + disable_nsfw=self.config.disable_nsfw_checker, + sd_cpu_textencoder=self.config.cpu_textencoder, + local_files_only=self.config.local_files_only, + cpu_offload=self.config.cpu_offload, + callback=diffuser_callback, + ) diff --git a/py/iopaint/batch_processing.py b/py/iopaint/batch_processing.py new file mode 100644 index 0000000..607e5a4 --- /dev/null +++ b/py/iopaint/batch_processing.py @@ -0,0 +1,127 @@ +import json +from pathlib import Path +from typing import Dict, Optional + +import cv2 +import psutil +from PIL import Image +from loguru import logger +from rich.console import Console +from rich.progress import ( + Progress, + SpinnerColumn, + TimeElapsedColumn, + MofNCompleteColumn, + TextColumn, + BarColumn, + TaskProgressColumn, +) + +from .helper import pil_to_bytes +from .model.utils import torch_gc +from .model_manager import ModelManager +from .schema import InpaintRequest + + +def glob_images(path: Path) -> Dict[str, Path]: + # png/jpg/jpeg + if path.is_file(): + return {path.stem: path} + elif path.is_dir(): + res = {} + for it in path.glob("*.*"): + if it.suffix.lower() in [".png", ".jpg", ".jpeg"]: + res[it.stem] = it + return res + + +def batch_inpaint( + model: str, + device, + image: Path, + mask: Path, + output: Path, + config: Optional[Path] = None, + concat: bool = False, +): + if image.is_dir() and output.is_file(): + logger.error( + f"invalid --output: when image is a directory, output should be a directory" + ) + exit(-1) + output.mkdir(parents=True, exist_ok=True) + + image_paths = glob_images(image) + mask_paths = glob_images(mask) + if len(image_paths) == 0: + logger.error(f"invalid --image: empty image folder") + exit(-1) + if len(mask_paths) == 0: + logger.error(f"invalid --mask: empty mask folder") + exit(-1) + + if config is None: + inpaint_request = InpaintRequest() + # logger.info(f"Using default config: {inpaint_request}") + else: + with open(config, "r", encoding="utf-8") as f: + inpaint_request = InpaintRequest(**json.load(f)) + + model_manager = ModelManager(name=model, device=device) + first_mask = list(mask_paths.values())[0] + + console = Console() + + with Progress( + SpinnerColumn(), + TextColumn("[progress.description]{task.description}"), + BarColumn(), + TaskProgressColumn(), + MofNCompleteColumn(), + TimeElapsedColumn(), + console=console, + transient=False, + ) as progress: + task = progress.add_task("Batch processing...", total=len(image_paths)) + for stem, image_p in image_paths.items(): + if stem not in mask_paths and mask.is_dir(): + progress.log(f"mask for {image_p} not found") + progress.update(task, advance=1) + continue + mask_p = mask_paths.get(stem, first_mask) + + infos = Image.open(image_p).info + + img = cv2.imread(str(image_p)) + img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) + mask_img = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + if mask_img.shape[:2] != img.shape[:2]: + progress.log( + f"resize mask {mask_p.name} to image {image_p.name} size: {img.shape[:2]}" + ) + mask_img = cv2.resize( + mask_img, + (img.shape[1], img.shape[0]), + interpolation=cv2.INTER_NEAREST, + ) + mask_img[mask_img >= 127] = 255 + mask_img[mask_img < 127] = 0 + + # bgr + inpaint_result = model_manager(img, mask_img, inpaint_request) + inpaint_result = cv2.cvtColor(inpaint_result, cv2.COLOR_BGR2RGB) + if concat: + mask_img = cv2.cvtColor(mask_img, cv2.COLOR_GRAY2RGB) + inpaint_result = cv2.hconcat([img, mask_img, inpaint_result]) + + img_bytes = pil_to_bytes(Image.fromarray(inpaint_result), "png", 100, infos) + save_p = output / f"{stem}.png" + with open(save_p, "wb") as fw: + fw.write(img_bytes) + + progress.update(task, advance=1) + torch_gc() + # pid = psutil.Process().pid + # memory_info = psutil.Process(pid).memory_info() + # memory_in_mb = memory_info.rss / (1024 * 1024) + # print(f"原图大小:{img.shape},当前进程的内存占用:{memory_in_mb}MB") diff --git a/py/iopaint/benchmark.py b/py/iopaint/benchmark.py new file mode 100644 index 0000000..f0b7cb9 --- /dev/null +++ b/py/iopaint/benchmark.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 + +import argparse +import os +import time + +import numpy as np +import nvidia_smi +import psutil +import torch + +from .model_manager import ModelManager +from .schema import InpaintRequest, HDStrategy, SDSampler + +try: + torch._C._jit_override_can_fuse_on_cpu(False) + torch._C._jit_override_can_fuse_on_gpu(False) + torch._C._jit_set_texpr_fuser_enabled(False) + torch._C._jit_set_nvfuser_enabled(False) +except: + pass + +NUM_THREADS = str(4) + +os.environ["OMP_NUM_THREADS"] = NUM_THREADS +os.environ["OPENBLAS_NUM_THREADS"] = NUM_THREADS +os.environ["MKL_NUM_THREADS"] = NUM_THREADS +os.environ["VECLIB_MAXIMUM_THREADS"] = NUM_THREADS +os.environ["NUMEXPR_NUM_THREADS"] = NUM_THREADS +if os.environ.get("CACHE_DIR"): + os.environ["TORCH_HOME"] = os.environ["CACHE_DIR"] + + +def run_model(model, size): + # RGB + image = np.random.randint(0, 256, (size[0], size[1], 3)).astype(np.uint8) + mask = np.random.randint(0, 255, size).astype(np.uint8) + + config = InpaintRequest( + ldm_steps=2, + hd_strategy=HDStrategy.ORIGINAL, + hd_strategy_crop_margin=128, + hd_strategy_crop_trigger_size=128, + hd_strategy_resize_limit=128, + prompt="a fox is sitting on a bench", + sd_steps=5, + sd_sampler=SDSampler.ddim, + ) + model(image, mask, config) + + +def benchmark(model, times: int, empty_cache: bool): + sizes = [(512, 512)] + + nvidia_smi.nvmlInit() + device_id = 0 + handle = nvidia_smi.nvmlDeviceGetHandleByIndex(device_id) + + def format(metrics): + return f"{np.mean(metrics):.2f} ± {np.std(metrics):.2f}" + + process = psutil.Process(os.getpid()) + # 每个 size 给出显存和内存占用的指标 + for size in sizes: + torch.cuda.empty_cache() + time_metrics = [] + cpu_metrics = [] + memory_metrics = [] + gpu_memory_metrics = [] + for _ in range(times): + start = time.time() + run_model(model, size) + torch.cuda.synchronize() + + # cpu_metrics.append(process.cpu_percent()) + time_metrics.append((time.time() - start) * 1000) + memory_metrics.append(process.memory_info().rss / 1024 / 1024) + gpu_memory_metrics.append( + nvidia_smi.nvmlDeviceGetMemoryInfo(handle).used / 1024 / 1024 + ) + + print(f"size: {size}".center(80, "-")) + # print(f"cpu: {format(cpu_metrics)}") + print(f"latency: {format(time_metrics)}ms") + print(f"memory: {format(memory_metrics)} MB") + print(f"gpu memory: {format(gpu_memory_metrics)} MB") + + nvidia_smi.nvmlShutdown() + + +def get_args_parser(): + parser = argparse.ArgumentParser() + parser.add_argument("--name") + parser.add_argument("--device", default="cuda", type=str) + parser.add_argument("--times", default=10, type=int) + parser.add_argument("--empty-cache", action="store_true") + return parser.parse_args() + + +if __name__ == "__main__": + args = get_args_parser() + device = torch.device(args.device) + model = ModelManager( + name=args.name, + device=device, + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + benchmark(model, args.times, args.empty_cache) diff --git a/py/iopaint/cli.py b/py/iopaint/cli.py new file mode 100644 index 0000000..5fdc975 --- /dev/null +++ b/py/iopaint/cli.py @@ -0,0 +1,220 @@ +import webbrowser +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Dict, Optional + +import typer +from fastapi import FastAPI +from loguru import logger +from typer import Option +from typer_config import use_json_config + +from .const import * +from .runtime import setup_model_dir, dump_environment_info, check_device +from .schema import InteractiveSegModel, Device, RealESRGANModel, RemoveBGModel + +typer_app = typer.Typer(pretty_exceptions_show_locals=False, add_completion=False) + + +@typer_app.command(help="Install all plugins dependencies") +def install_plugins_packages(): + from .installer import install_plugins_package + + install_plugins_package() + + +@typer_app.command(help="Download SD/SDXL normal/inpainting model from HuggingFace") +def download( + model: str = Option( + ..., help="Model id on HuggingFace e.g: runwayml/stable-diffusion-inpainting" + ), + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import cli_download_model + + cli_download_model(model) + + +@typer_app.command(name="list", help="List downloaded models") +def list_model( + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import scan_models + + scanned_models = scan_models() + for it in scanned_models: + print(it.name) + + +@typer_app.command(help="Batch processing images") +def run( + model: str = Option("lama"), + device: Device = Option(Device.cpu), + image: Path = Option(..., help="Image folders or file path"), + mask: Path = Option( + ..., + help="Mask folders or file path. " + "If it is a directory, the mask images in the directory should have the same name as the original image." + "If it is a file, all images will use this mask." + "Mask will automatically resize to the same size as the original image.", + ), + output: Path = Option(..., help="Output directory or file path"), + config: Path = None, + concat: bool = False, + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + file_okay=False, + callback=setup_model_dir, + ), +): + from .download import cli_download_model, scan_models + + scanned_models = scan_models() + if model not in [it.name for it in scanned_models]: + logger.info(f"{model} not found in {model_dir}, try to downloading") + cli_download_model(model) + + from .batch_processing import batch_inpaint + + + batch_inpaint(model, device, image, mask, output, config, concat) + + +@typer_app.command(help="Start IOPaint server") +@use_json_config() +def start( + host: str = Option("127.0.0.1"), + port: int = Option(8080), + inbrowser: bool = Option(False, help=INBROWSER_HELP), + model: str = Option( + DEFAULT_MODEL, + help=f"Erase models: [{', '.join(AVAILABLE_MODELS)}].\n" + f"Diffusion models: [{', '.join(DIFFUSION_MODELS)}] or any SD/SDXL normal/inpainting models on HuggingFace.", + ), + model_dir: Path = Option( + DEFAULT_MODEL_DIR, + help=MODEL_DIR_HELP, + dir_okay=True, + file_okay=False, + callback=setup_model_dir, + ), + low_mem: bool = Option(False, help=LOW_MEM_HELP), + no_half: bool = Option(False, help=NO_HALF_HELP), + cpu_offload: bool = Option(False, help=CPU_OFFLOAD_HELP), + disable_nsfw_checker: bool = Option(False, help=DISABLE_NSFW_HELP), + cpu_textencoder: bool = Option(False, help=CPU_TEXTENCODER_HELP), + local_files_only: bool = Option(False, help=LOCAL_FILES_ONLY_HELP), + device: Device = Option(Device.cpu), + input: Optional[Path] = Option(None, help=INPUT_HELP), + output_dir: Optional[Path] = Option( + None, help=OUTPUT_DIR_HELP, dir_okay=True, file_okay=False + ), + quality: int = Option(95, help=QUALITY_HELP), + enable_interactive_seg: bool = Option(False, help=INTERACTIVE_SEG_HELP), + interactive_seg_model: InteractiveSegModel = Option( + InteractiveSegModel.vit_b, help=INTERACTIVE_SEG_MODEL_HELP + ), + interactive_seg_device: Device = Option(Device.cpu), + enable_remove_bg: bool = Option(False, help=REMOVE_BG_HELP), + remove_bg_model: RemoveBGModel = Option(RemoveBGModel.briaai_rmbg_1_4), + enable_anime_seg: bool = Option(False, help=ANIMESEG_HELP), + enable_realesrgan: bool = Option(False), + realesrgan_device: Device = Option(Device.cpu), + realesrgan_model: RealESRGANModel = Option(RealESRGANModel.realesr_general_x4v3), + enable_gfpgan: bool = Option(False), + gfpgan_device: Device = Option(Device.cpu), + enable_restoreformer: bool = Option(False), + restoreformer_device: Device = Option(Device.cpu), +): + dump_environment_info() + device = check_device(device) + if input and not input.exists(): + logger.error(f"invalid --input: {input} not exists") + exit(-1) + if input and input.is_dir() and not output_dir: + logger.error(f"invalid --output-dir: must be set when --input is a directory") + exit(-1) + if output_dir: + output_dir = output_dir.expanduser().absolute() + logger.info(f"Image will be saved to {output_dir}") + if not output_dir.exists(): + logger.info(f"Create output directory {output_dir}") + output_dir.mkdir(parents=True) + + model_dir = model_dir.expanduser().absolute() + + if local_files_only: + os.environ["TRANSFORMERS_OFFLINE"] = "1" + os.environ["HF_HUB_OFFLINE"] = "1" + + from .download import cli_download_model, scan_models + + scanned_models = scan_models() + if model not in [it.name for it in scanned_models]: + logger.info(f"{model} not found in {model_dir}, try to downloading") + cli_download_model(model) + + from .api import Api + from .schema import ApiConfig + + @asynccontextmanager + async def lifespan(app: FastAPI): + if inbrowser: + webbrowser.open(f"http://localhost:{port}", new=0, autoraise=True) + yield + + app = FastAPI(lifespan=lifespan) + + api_config = ApiConfig( + host=host, + port=port, + inbrowser=inbrowser, + model=model, + no_half=no_half, + low_mem=low_mem, + cpu_offload=cpu_offload, + disable_nsfw_checker=disable_nsfw_checker, + local_files_only=local_files_only, + cpu_textencoder=cpu_textencoder if device == Device.cuda else False, + device=device, + input=input, + output_dir=output_dir, + quality=quality, + enable_interactive_seg=enable_interactive_seg, + interactive_seg_model=interactive_seg_model, + interactive_seg_device=interactive_seg_device, + enable_remove_bg=enable_remove_bg, + remove_bg_model=remove_bg_model, + enable_anime_seg=enable_anime_seg, + enable_realesrgan=enable_realesrgan, + realesrgan_device=realesrgan_device, + realesrgan_model=realesrgan_model, + enable_gfpgan=enable_gfpgan, + gfpgan_device=gfpgan_device, + enable_restoreformer=enable_restoreformer, + restoreformer_device=restoreformer_device, + ) + # print(api_config.model_dump_json(indent=4)) + api = Api(app, api_config) + api.launch() + + +@typer_app.command(help="Start IOPaint web config page") +def start_web_config( + config_file: Path = Option("config.json"), +): + dump_environment_info() + from .web_config import main + + main(config_file) diff --git a/py/iopaint/const.py b/py/iopaint/const.py new file mode 100644 index 0000000..4d64d1e --- /dev/null +++ b/py/iopaint/const.py @@ -0,0 +1,125 @@ +import os +from typing import List +import folder_paths + +INSTRUCT_PIX2PIX_NAME = "timbrooks/instruct-pix2pix" +KANDINSKY22_NAME = "kandinsky-community/kandinsky-2-2-decoder-inpaint" +POWERPAINT_NAME = "Sanster/PowerPaint-V1-stable-diffusion-inpainting" +ANYTEXT_NAME = "Sanster/AnyText" + + +DIFFUSERS_SD_CLASS_NAME = "StableDiffusionPipeline" +DIFFUSERS_SD_INPAINT_CLASS_NAME = "StableDiffusionInpaintPipeline" +DIFFUSERS_SDXL_CLASS_NAME = "StableDiffusionXLPipeline" +DIFFUSERS_SDXL_INPAINT_CLASS_NAME = "StableDiffusionXLInpaintPipeline" + +MPS_UNSUPPORT_MODELS = [ + "lama", + "ldm", + "zits", + "mat", + "fcf", + "cv2", + "manga", +] + +DEFAULT_MODEL = "lama" +AVAILABLE_MODELS = ["lama", "ldm", "zits", "mat", "fcf", "manga", "cv2", "migan"] +DIFFUSION_MODELS = [ + "runwayml/stable-diffusion-inpainting", + "Uminosachi/realisticVisionV51_v51VAE-inpainting", + "redstonehero/dreamshaper-inpainting", + "Sanster/anything-4.0-inpainting", + "diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + "Fantasy-Studio/Paint-by-Example", + POWERPAINT_NAME, + ANYTEXT_NAME, +] + +NO_HALF_HELP = """ +Using full precision(fp32) model. +If your diffusion model generate result is always black or green, use this argument. +""" + +CPU_OFFLOAD_HELP = """ +Offloads diffusion model's weight to CPU RAM, significantly reducing vRAM usage. +""" + +LOW_MEM_HELP = "Enable attention slicing and vae tiling to save memory." + +DISABLE_NSFW_HELP = """ +Disable NSFW checker for diffusion model. +""" + +CPU_TEXTENCODER_HELP = """ +Run diffusion models text encoder on CPU to reduce vRAM usage. +""" + +SD_CONTROLNET_CHOICES: List[str] = [ + "lllyasviel/control_v11p_sd15_canny", + # "lllyasviel/control_v11p_sd15_seg", + "lllyasviel/control_v11p_sd15_openpose", + "lllyasviel/control_v11p_sd15_inpaint", + "lllyasviel/control_v11f1p_sd15_depth", +] + +SD2_CONTROLNET_CHOICES = [ + "thibaud/controlnet-sd21-canny-diffusers", + "thibaud/controlnet-sd21-depth-diffusers", + "thibaud/controlnet-sd21-openpose-diffusers", +] + +SDXL_CONTROLNET_CHOICES = [ + "thibaud/controlnet-openpose-sdxl-1.0", + "destitech/controlnet-inpaint-dreamer-sdxl", + "diffusers/controlnet-canny-sdxl-1.0", + "diffusers/controlnet-canny-sdxl-1.0-mid", + "diffusers/controlnet-canny-sdxl-1.0-small", + "diffusers/controlnet-depth-sdxl-1.0", + "diffusers/controlnet-depth-sdxl-1.0-mid", + "diffusers/controlnet-depth-sdxl-1.0-small", +] + +LOCAL_FILES_ONLY_HELP = """ +When loading diffusion models, using local files only, not connect to HuggingFace server. +""" + +# DEFAULT_MODEL_DIR = os.path.abspath( +# os.getenv("XDG_CACHE_HOME", os.path.join(os.path.expanduser("~"), ".cache")) +# ) + + +DEFAULT_MODEL_DIR = os.path.abspath(os.path.join(folder_paths.models_dir, 'lama')) +# print(f"DEFAULT_MODEL_DIR={DEFAULT_MODEL_DIR}") + +MODEL_DIR_HELP = f""" +Model download directory (by setting XDG_CACHE_HOME environment variable), by default model download to {DEFAULT_MODEL_DIR} +""" + +OUTPUT_DIR_HELP = """ +Result images will be saved to output directory automatically. +""" + +INPUT_HELP = """ +If input is image, it will be loaded by default. +If input is directory, you can browse and select image in file manager. +""" + +GUI_HELP = """ +Launch Lama Cleaner as desktop app +""" + +QUALITY_HELP = """ +Quality of image encoding, 0-100. Default is 95, higher quality will generate larger file size. +""" + +INTERACTIVE_SEG_HELP = "Enable interactive segmentation using Segment Anything." +INTERACTIVE_SEG_MODEL_HELP = "Model size: mobile_sam < vit_b < vit_l < vit_h. Bigger model size means better segmentation but slower speed." +REMOVE_BG_HELP = "Enable remove background plugin. Always run on CPU" +ANIMESEG_HELP = "Enable anime segmentation plugin. Always run on CPU" +REALESRGAN_HELP = "Enable realesrgan super resolution" +GFPGAN_HELP = "Enable GFPGAN face restore. To also enhance background, use with --enable-realesrgan" +RESTOREFORMER_HELP = "Enable RestoreFormer face restore. To also enhance background, use with --enable-realesrgan" +GIF_HELP = "Enable GIF plugin. Make GIF to compare original and cleaned image" + +INBROWSER_HELP = "Automatically launch IOPaint in a new tab on the default browser" diff --git a/py/iopaint/download.py b/py/iopaint/download.py new file mode 100644 index 0000000..53c441f --- /dev/null +++ b/py/iopaint/download.py @@ -0,0 +1,294 @@ +import json +import os +from functools import lru_cache +from typing import List + +from .schema import ModelType, ModelInfo +from loguru import logger +from pathlib import Path + +from .const import ( + DEFAULT_MODEL_DIR, + DIFFUSERS_SD_CLASS_NAME, + DIFFUSERS_SD_INPAINT_CLASS_NAME, + DIFFUSERS_SDXL_CLASS_NAME, + DIFFUSERS_SDXL_INPAINT_CLASS_NAME, + ANYTEXT_NAME, +) +from .model.original_sd_configs import get_config_files + + +def cli_download_model(model: str): + from .model import models + from .model.utils import handle_from_pretrained_exceptions + + if model in models and models[model].is_erase_model: + logger.info(f"Downloading {model}...") + models[model].download() + logger.info(f"Done.") + elif model == ANYTEXT_NAME: + logger.info(f"Downloading {model}...") + models[model].download() + logger.info(f"Done.") + else: + logger.info(f"Downloading model from Huggingface: {model}") + from diffusers import DiffusionPipeline + + downloaded_path = handle_from_pretrained_exceptions( + DiffusionPipeline.download, + pretrained_model_name=model, + variant="fp16", + resume_download=True, + ) + logger.info(f"Done. Downloaded to {downloaded_path}") + + +def folder_name_to_show_name(name: str) -> str: + return name.replace("models--", "").replace("--", "/") + + +@lru_cache(maxsize=512) +def get_sd_model_type(model_abs_path: str) -> ModelType: + if "inpaint" in Path(model_abs_path).name.lower(): + model_type = ModelType.DIFFUSERS_SD_INPAINT + else: + # load once to check num_in_channels + from diffusers import StableDiffusionInpaintPipeline + + try: + StableDiffusionInpaintPipeline.from_single_file( + model_abs_path, + load_safety_checker=False, + num_in_channels=9, + config_files=get_config_files(), + ) + model_type = ModelType.DIFFUSERS_SD_INPAINT + except ValueError as e: + if "Trying to set a tensor of shape torch.Size([320, 4, 3, 3])" in str(e): + model_type = ModelType.DIFFUSERS_SD + else: + raise e + return model_type + + +@lru_cache() +def get_sdxl_model_type(model_abs_path: str) -> ModelType: + if "inpaint" in model_abs_path: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + # load once to check num_in_channels + from diffusers import StableDiffusionXLInpaintPipeline + + try: + model = StableDiffusionXLInpaintPipeline.from_single_file( + model_abs_path, + load_safety_checker=False, + num_in_channels=9, + config_files=get_config_files(), + ) + if model.unet.config.in_channels == 9: + # https://github.com/huggingface/diffusers/issues/6610 + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + model_type = ModelType.DIFFUSERS_SDXL + except ValueError as e: + if "Trying to set a tensor of shape torch.Size([320, 4, 3, 3])" in str(e): + model_type = ModelType.DIFFUSERS_SDXL + else: + raise e + return model_type + + +def scan_single_file_diffusion_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + stable_diffusion_dir = cache_dir / "stable_diffusion" + cache_file = stable_diffusion_dir / "iopaint_cache.json" + model_type_cache = {} + if cache_file.exists(): + try: + with open(cache_file, "r", encoding="utf-8") as f: + model_type_cache = json.load(f) + assert isinstance(model_type_cache, dict) + except: + pass + + res = [] + for it in stable_diffusion_dir.glob(f"*.*"): + if it.suffix not in [".safetensors", ".ckpt"]: + continue + model_abs_path = str(it.absolute()) + model_type = model_type_cache.get(it.name) + if model_type is None: + model_type = get_sd_model_type(model_abs_path) + model_type_cache[it.name] = model_type + res.append( + ModelInfo( + name=it.name, + path=model_abs_path, + model_type=model_type, + is_single_file_diffusers=True, + ) + ) + if stable_diffusion_dir.exists(): + with open(cache_file, "w", encoding="utf-8") as fw: + json.dump(model_type_cache, fw, indent=2, ensure_ascii=False) + + stable_diffusion_xl_dir = cache_dir / "stable_diffusion_xl" + sdxl_cache_file = stable_diffusion_xl_dir / "iopaint_cache.json" + sdxl_model_type_cache = {} + if sdxl_cache_file.exists(): + try: + with open(sdxl_cache_file, "r", encoding="utf-8") as f: + sdxl_model_type_cache = json.load(f) + assert isinstance(sdxl_model_type_cache, dict) + except: + pass + + for it in stable_diffusion_xl_dir.glob(f"*.*"): + if it.suffix not in [".safetensors", ".ckpt"]: + continue + model_abs_path = str(it.absolute()) + model_type = sdxl_model_type_cache.get(it.name) + if model_type is None: + model_type = get_sdxl_model_type(model_abs_path) + sdxl_model_type_cache[it.name] = model_type + if stable_diffusion_xl_dir.exists(): + with open(sdxl_cache_file, "w", encoding="utf-8") as fw: + json.dump(sdxl_model_type_cache, fw, indent=2, ensure_ascii=False) + + res.append( + ModelInfo( + name=it.name, + path=model_abs_path, + model_type=model_type, + is_single_file_diffusers=True, + ) + ) + return res + + +def scan_inpaint_models(model_dir: Path) -> List[ModelInfo]: + res = [] + from .model import models + + # logger.info(f"Scanning inpaint models in {model_dir}") + + for name, m in models.items(): + if m.is_erase_model and m.is_downloaded(): + res.append( + ModelInfo( + name=name, + path=name, + model_type=ModelType.INPAINT, + ) + ) + return res + + +def scan_diffusers_models() -> List[ModelInfo]: + from huggingface_hub.constants import HF_HUB_CACHE + + available_models = [] + cache_dir = Path(HF_HUB_CACHE) + # logger.info(f"Scanning diffusers models in {cache_dir}") + diffusers_model_names = [] + for it in cache_dir.glob("**/*/model_index.json"): + with open(it, "r", encoding="utf-8") as f: + try: + data = json.load(f) + except: + continue + + _class_name = data["_class_name"] + name = folder_name_to_show_name(it.parent.parent.parent.name) + if name in diffusers_model_names: + continue + if "PowerPaint" in name: + model_type = ModelType.DIFFUSERS_OTHER + elif _class_name == DIFFUSERS_SD_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD + elif _class_name == DIFFUSERS_SD_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD_INPAINT + elif _class_name == DIFFUSERS_SDXL_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL + elif _class_name == DIFFUSERS_SDXL_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + elif _class_name in [ + "StableDiffusionInstructPix2PixPipeline", + "PaintByExamplePipeline", + "KandinskyV22InpaintPipeline", + "AnyText", + ]: + model_type = ModelType.DIFFUSERS_OTHER + else: + continue + + diffusers_model_names.append(name) + available_models.append( + ModelInfo( + name=name, + path=name, + model_type=model_type, + ) + ) + return available_models + + +def _scan_converted_diffusers_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + available_models = [] + diffusers_model_names = [] + for it in cache_dir.glob("**/*/model_index.json"): + with open(it, "r", encoding="utf-8") as f: + try: + data = json.load(f) + except: + logger.error( + f"Failed to load {it}, please try revert from original model or fix model_index.json by hand." + ) + continue + + _class_name = data["_class_name"] + name = folder_name_to_show_name(it.parent.name) + if name in diffusers_model_names: + continue + elif _class_name == DIFFUSERS_SD_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD + elif _class_name == DIFFUSERS_SD_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SD_INPAINT + elif _class_name == DIFFUSERS_SDXL_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL + elif _class_name == DIFFUSERS_SDXL_INPAINT_CLASS_NAME: + model_type = ModelType.DIFFUSERS_SDXL_INPAINT + else: + continue + + diffusers_model_names.append(name) + available_models.append( + ModelInfo( + name=name, + path=str(it.parent.absolute()), + model_type=model_type, + ) + ) + return available_models + + +def scan_converted_diffusers_models(cache_dir) -> List[ModelInfo]: + cache_dir = Path(cache_dir) + available_models = [] + stable_diffusion_dir = cache_dir / "stable_diffusion" + stable_diffusion_xl_dir = cache_dir / "stable_diffusion_xl" + available_models.extend(_scan_converted_diffusers_models(stable_diffusion_dir)) + available_models.extend(_scan_converted_diffusers_models(stable_diffusion_xl_dir)) + return available_models + + +def scan_models() -> List[ModelInfo]: + model_dir = os.getenv("XDG_CACHE_HOME", DEFAULT_MODEL_DIR) + available_models = [] + available_models.extend(scan_inpaint_models(model_dir)) + available_models.extend(scan_single_file_diffusion_models(model_dir)) + available_models.extend(scan_diffusers_models()) + available_models.extend(scan_converted_diffusers_models(model_dir)) + return available_models diff --git a/py/iopaint/file_manager/__init__.py b/py/iopaint/file_manager/__init__.py new file mode 100644 index 0000000..1a24998 --- /dev/null +++ b/py/iopaint/file_manager/__init__.py @@ -0,0 +1 @@ +from .file_manager import FileManager diff --git a/py/iopaint/file_manager/file_manager.py b/py/iopaint/file_manager/file_manager.py new file mode 100644 index 0000000..413162c --- /dev/null +++ b/py/iopaint/file_manager/file_manager.py @@ -0,0 +1,215 @@ +import os +from io import BytesIO +from pathlib import Path +from typing import List + +from PIL import Image, ImageOps, PngImagePlugin +from fastapi import FastAPI, UploadFile, HTTPException +from starlette.responses import FileResponse + +from ..schema import MediasResponse, MediaTab + +LARGE_ENOUGH_NUMBER = 100 +PngImagePlugin.MAX_TEXT_CHUNK = LARGE_ENOUGH_NUMBER * (1024**2) +from .storage_backends import FilesystemStorageBackend +from .utils import aspect_to_string, generate_filename, glob_img + + +class FileManager: + def __init__(self, app: FastAPI, input_dir: Path, output_dir: Path): + self.app = app + self.input_dir: Path = input_dir + self.output_dir: Path = output_dir + + self.image_dir_filenames = [] + self.output_dir_filenames = [] + if not self.thumbnail_directory.exists(): + self.thumbnail_directory.mkdir(parents=True) + + # fmt: off + self.app.add_api_route("/api/v1/medias", self.api_medias, methods=["GET"], response_model=List[MediasResponse]) + self.app.add_api_route("/api/v1/media_file", self.api_media_file, methods=["GET"]) + self.app.add_api_route("/api/v1/media_thumbnail_file", self.api_media_thumbnail_file, methods=["GET"]) + # fmt: on + + def api_medias(self, tab: MediaTab) -> List[MediasResponse]: + img_dir = self._get_dir(tab) + return self._media_names(img_dir) + + def api_media_file(self, tab: MediaTab, filename: str) -> FileResponse: + file_path = self._get_file(tab, filename) + return FileResponse(file_path, media_type="image/png") + + # tab=${tab}?filename=${filename.name}?width=${width}&height=${height} + def api_media_thumbnail_file( + self, tab: MediaTab, filename: str, width: int, height: int + ) -> FileResponse: + img_dir = self._get_dir(tab) + thumb_filename, (width, height) = self.get_thumbnail( + img_dir, filename, width=width, height=height + ) + thumbnail_filepath = self.thumbnail_directory / thumb_filename + return FileResponse( + thumbnail_filepath, + headers={ + "X-Width": str(width), + "X-Height": str(height), + }, + media_type="image/jpeg", + ) + + def _get_dir(self, tab: MediaTab) -> Path: + if tab == "input": + return self.input_dir + elif tab == "output": + return self.output_dir + else: + raise HTTPException(status_code=422, detail=f"tab not found: {tab}") + + def _get_file(self, tab: MediaTab, filename: str) -> Path: + file_path = self._get_dir(tab) / filename + if not file_path.exists(): + raise HTTPException(status_code=422, detail=f"file not found: {file_path}") + return file_path + + @property + def thumbnail_directory(self) -> Path: + return self.output_dir / "thumbnails" + + @staticmethod + def _media_names(directory: Path) -> List[MediasResponse]: + names = sorted([it.name for it in glob_img(directory)]) + res = [] + for name in names: + path = os.path.join(directory, name) + img = Image.open(path) + res.append( + MediasResponse( + name=name, + height=img.height, + width=img.width, + ctime=os.path.getctime(path), + mtime=os.path.getmtime(path), + ) + ) + return res + + def get_thumbnail( + self, directory: Path, original_filename: str, width, height, **options + ): + directory = Path(directory) + storage = FilesystemStorageBackend(self.app) + crop = options.get("crop", "fit") + background = options.get("background") + quality = options.get("quality", 90) + + original_path, original_filename = os.path.split(original_filename) + original_filepath = os.path.join(directory, original_path, original_filename) + image = Image.open(BytesIO(storage.read(original_filepath))) + + # keep ratio resize + if not width and not height: + width = 256 + + if width != 0: + height = int(image.height * width / image.width) + else: + width = int(image.width * height / image.height) + + thumbnail_size = (width, height) + + thumbnail_filename = generate_filename( + directory, + original_filename, + aspect_to_string(thumbnail_size), + crop, + background, + quality, + ) + + thumbnail_filepath = os.path.join( + self.thumbnail_directory, original_path, thumbnail_filename + ) + + if storage.exists(thumbnail_filepath): + return thumbnail_filepath, (width, height) + + try: + image.load() + except (IOError, OSError): + self.app.logger.warning("Thumbnail not load image: %s", original_filepath) + return thumbnail_filepath, (width, height) + + # get original image format + options["format"] = options.get("format", image.format) + + image = self._create_thumbnail( + image, thumbnail_size, crop, background=background + ) + + raw_data = self.get_raw_data(image, **options) + storage.save(thumbnail_filepath, raw_data) + + return thumbnail_filepath, (width, height) + + def get_raw_data(self, image, **options): + data = { + "format": self._get_format(image, **options), + "quality": options.get("quality", 90), + } + + _file = BytesIO() + image.save(_file, **data) + return _file.getvalue() + + @staticmethod + def colormode(image, colormode="RGB"): + if colormode == "RGB" or colormode == "RGBA": + if image.mode == "RGBA": + return image + if image.mode == "LA": + return image.convert("RGBA") + return image.convert(colormode) + + if colormode == "GRAY": + return image.convert("L") + + return image.convert(colormode) + + @staticmethod + def background(original_image, color=0xFF): + size = (max(original_image.size),) * 2 + image = Image.new("L", size, color) + image.paste( + original_image, + tuple(map(lambda x: (x[0] - x[1]) / 2, zip(size, original_image.size))), + ) + + return image + + def _get_format(self, image, **options): + if options.get("format"): + return options.get("format") + if image.format: + return image.format + + return "JPEG" + + def _create_thumbnail(self, image, size, crop="fit", background=None): + try: + resample = Image.Resampling.LANCZOS + except AttributeError: # pylint: disable=raise-missing-from + resample = Image.ANTIALIAS + + if crop == "fit": + image = ImageOps.fit(image, size, resample) + else: + image = image.copy() + image.thumbnail(size, resample=resample) + + if background is not None: + image = self.background(image) + + image = self.colormode(image) + + return image diff --git a/py/iopaint/file_manager/storage_backends.py b/py/iopaint/file_manager/storage_backends.py new file mode 100644 index 0000000..3f453ad --- /dev/null +++ b/py/iopaint/file_manager/storage_backends.py @@ -0,0 +1,46 @@ +# Copy from https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/storage_backends.py +import errno +import os +from abc import ABC, abstractmethod + + +class BaseStorageBackend(ABC): + def __init__(self, app=None): + self.app = app + + @abstractmethod + def read(self, filepath, mode="rb", **kwargs): + raise NotImplementedError + + @abstractmethod + def exists(self, filepath): + raise NotImplementedError + + @abstractmethod + def save(self, filepath, data): + raise NotImplementedError + + +class FilesystemStorageBackend(BaseStorageBackend): + def read(self, filepath, mode="rb", **kwargs): + with open(filepath, mode) as f: # pylint: disable=unspecified-encoding + return f.read() + + def exists(self, filepath): + return os.path.exists(filepath) + + def save(self, filepath, data): + directory = os.path.dirname(filepath) + + if not os.path.exists(directory): + try: + os.makedirs(directory) + except OSError as e: + if e.errno != errno.EEXIST: + raise + + if not os.path.isdir(directory): + raise IOError("{} is not a directory".format(directory)) + + with open(filepath, "wb") as f: + f.write(data) diff --git a/py/iopaint/file_manager/utils.py b/py/iopaint/file_manager/utils.py new file mode 100644 index 0000000..f6890af --- /dev/null +++ b/py/iopaint/file_manager/utils.py @@ -0,0 +1,65 @@ +# Copy from: https://github.com/silentsokolov/flask-thumbnails/blob/master/flask_thumbnails/utils.py +import hashlib +from pathlib import Path + +from typing import Union + + +def generate_filename(directory: Path, original_filename, *options) -> str: + text = str(directory.absolute()) + original_filename + for v in options: + text += "%s" % v + md5_hash = hashlib.md5() + md5_hash.update(text.encode("utf-8")) + return md5_hash.hexdigest() + ".jpg" + + +def parse_size(size): + if isinstance(size, int): + # If the size parameter is a single number, assume square aspect. + return [size, size] + + if isinstance(size, (tuple, list)): + if len(size) == 1: + # If single value tuple/list is provided, exand it to two elements + return size + type(size)(size) + return size + + try: + thumbnail_size = [int(x) for x in size.lower().split("x", 1)] + except ValueError: + raise ValueError( # pylint: disable=raise-missing-from + "Bad thumbnail size format. Valid format is INTxINT." + ) + + if len(thumbnail_size) == 1: + # If the size parameter only contains a single integer, assume square aspect. + thumbnail_size.append(thumbnail_size[0]) + + return thumbnail_size + + +def aspect_to_string(size): + if isinstance(size, str): + return size + + return "x".join(map(str, size)) + + +IMG_SUFFIX = {".jpg", ".jpeg", ".png", ".JPG", ".JPEG", ".PNG"} + + +def glob_img(p: Union[Path, str], recursive: bool = False): + p = Path(p) + if p.is_file() and p.suffix in IMG_SUFFIX: + yield p + else: + if recursive: + files = Path(p).glob("**/*.*") + else: + files = Path(p).glob("*.*") + + for it in files: + if it.suffix not in IMG_SUFFIX: + continue + yield it diff --git a/py/iopaint/helper.py b/py/iopaint/helper.py new file mode 100644 index 0000000..35d348e --- /dev/null +++ b/py/iopaint/helper.py @@ -0,0 +1,411 @@ +import base64 +import imghdr +import io +import os +import sys +from typing import List, Optional, Dict, Tuple + +from urllib.parse import urlparse +import cv2 +from PIL import Image, ImageOps, PngImagePlugin +import numpy as np +import torch +from .const import MPS_UNSUPPORT_MODELS +from loguru import logger +from torch.hub import download_url_to_file, get_dir +import hashlib +from .const import DEFAULT_MODEL_DIR + + +def md5sum(filename): + md5 = hashlib.md5() + with open(filename, "rb") as f: + for chunk in iter(lambda: f.read(128 * md5.block_size), b""): + md5.update(chunk) + return md5.hexdigest() + + +def switch_mps_device(model_name, device): + if model_name in MPS_UNSUPPORT_MODELS and str(device) == "mps": + logger.info(f"{model_name} not support mps, switch to cpu") + return torch.device("cpu") + return device + + +def get_cache_path_by_url(url): + parts = urlparse(url) + # hub_dir = get_dir() + # model_dir = os.path.join(hub_dir, "checkpoints") + model_dir = DEFAULT_MODEL_DIR + if not os.path.isdir(model_dir): + os.makedirs(model_dir) + filename = os.path.basename(parts.path) + cached_file = os.path.join(model_dir, filename) + return cached_file + + +def download_model(url, model_md5: str = None): + if os.path.exists(url): + cached_file = url + else: + cached_file = get_cache_path_by_url(url) + if not os.path.exists(cached_file): + sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file)) + hash_prefix = None + download_url_to_file(url, cached_file, hash_prefix, progress=True) + if model_md5: + _md5 = md5sum(cached_file) + if model_md5 == _md5: + logger.info(f"Download model success, md5: {_md5}") + else: + try: + os.remove(cached_file) + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, wrong model deleted. Please restart iopaint." + f"If you still have errors, please try download model manually first https://lama-cleaner-docs.vercel.app/install/download_model_manually.\n" + ) + except: + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, please delete {cached_file} and restart iopaint." + ) + exit(-1) + + return cached_file + + +def ceil_modulo(x, mod): + if x % mod == 0: + return x + return (x // mod + 1) * mod + + +def handle_error(model_path, model_md5, e): + _md5 = md5sum(model_path) + if _md5 != model_md5: + try: + os.remove(model_path) + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, wrong model deleted. Please restart iopaint." + f"If you still have errors, please try download model manually first https://lama-cleaner-docs.vercel.app/install/download_model_manually.\n" + ) + except: + logger.error( + f"Model md5: {_md5}, expected md5: {model_md5}, please delete {model_path} and restart iopaint." + ) + else: + logger.error( + f"Failed to load model {model_path}," + f"please submit an issue at https://github.com/Sanster/lama-cleaner/issues and include a screenshot of the error:\n{e}" + ) + exit(-1) + + +def load_jit_model(url_or_path, device, model_md5: str): + if os.path.exists(url_or_path): + model_path = url_or_path + else: + model_path = download_model(url_or_path, model_md5) + model_path = os.path.normpath(model_path) + logger.info(f"Loading model from: {model_path}") + + try: + model = torch.jit.load(model_path, map_location="cpu").to(device) + except Exception as e: + handle_error(model_path, model_md5, e) + model.eval() + return model + + +def load_model(model: torch.nn.Module, url_or_path, device, model_md5): + if os.path.exists(url_or_path): + model_path = url_or_path + else: + model_path = download_model(url_or_path, model_md5) + + try: + logger.info(f"Loading model from: {model_path}") + state_dict = torch.load(model_path, map_location="cpu") + model.load_state_dict(state_dict, strict=True) + model.to(device) + except Exception as e: + handle_error(model_path, model_md5, e) + model.eval() + return model + + +def numpy_to_bytes(image_numpy: np.ndarray, ext: str) -> bytes: + data = cv2.imencode( + f".{ext}", + image_numpy, + [int(cv2.IMWRITE_JPEG_QUALITY), 100, int(cv2.IMWRITE_PNG_COMPRESSION), 0], + )[1] + image_bytes = data.tobytes() + return image_bytes + + +def pil_to_bytes(pil_img, ext: str, quality: int = 95, infos={}) -> bytes: + with io.BytesIO() as output: + kwargs = {k: v for k, v in infos.items() if v is not None} + if ext == "jpg": + ext = "jpeg" + if "png" == ext.lower() and "parameters" in kwargs: + pnginfo_data = PngImagePlugin.PngInfo() + pnginfo_data.add_text("parameters", kwargs["parameters"]) + kwargs["pnginfo"] = pnginfo_data + + pil_img.save(output, format=ext, quality=quality, **kwargs) + image_bytes = output.getvalue() + return image_bytes + + +def load_img(img_bytes, gray: bool = False, return_info: bool = False): + alpha_channel = None + image = Image.open(io.BytesIO(img_bytes)) + + if return_info: + infos = image.info + + try: + image = ImageOps.exif_transpose(image) + except: + pass + + if gray: + image = image.convert("L") + np_img = np.array(image) + else: + if image.mode == "RGBA": + np_img = np.array(image) + alpha_channel = np_img[:, :, -1] + np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2RGB) + else: + image = image.convert("RGB") + np_img = np.array(image) + + if return_info: + return np_img, alpha_channel, infos + return np_img, alpha_channel + + +def norm_img(np_img): + if len(np_img.shape) == 2: + np_img = np_img[:, :, np.newaxis] + np_img = np.transpose(np_img, (2, 0, 1)) + np_img = np_img.astype("float32") / 255 + return np_img + + +def resize_max_size( + np_img, size_limit: int, interpolation=cv2.INTER_CUBIC +) -> np.ndarray: + # Resize image's longer size to size_limit if longer size larger than size_limit + h, w = np_img.shape[:2] + if max(h, w) > size_limit: + ratio = size_limit / max(h, w) + new_w = int(w * ratio + 0.5) + new_h = int(h * ratio + 0.5) + return cv2.resize(np_img, dsize=(new_w, new_h), interpolation=interpolation) + else: + return np_img + + +def pad_img_to_modulo( + img: np.ndarray, mod: int, square: bool = False, min_size: Optional[int] = None +): + """ + + Args: + img: [H, W, C] + mod: + square: 是否为正方形 + min_size: + + Returns: + + """ + if len(img.shape) == 2: + img = img[:, :, np.newaxis] + height, width = img.shape[:2] + out_height = ceil_modulo(height, mod) + out_width = ceil_modulo(width, mod) + + if min_size is not None: + assert min_size % mod == 0 + out_width = max(min_size, out_width) + out_height = max(min_size, out_height) + + if square: + max_size = max(out_height, out_width) + out_height = max_size + out_width = max_size + + return np.pad( + img, + ((0, out_height - height), (0, out_width - width), (0, 0)), + mode="symmetric", + ) + + +def boxes_from_mask(mask: np.ndarray) -> List[np.ndarray]: + """ + Args: + mask: (h, w, 1) 0~255 + + Returns: + + """ + height, width = mask.shape[:2] + _, thresh = cv2.threshold(mask, 127, 255, 0) + contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + boxes = [] + for cnt in contours: + x, y, w, h = cv2.boundingRect(cnt) + box = np.array([x, y, x + w, y + h]).astype(int) + + box[::2] = np.clip(box[::2], 0, width) + box[1::2] = np.clip(box[1::2], 0, height) + boxes.append(box) + + return boxes + + +def only_keep_largest_contour(mask: np.ndarray) -> List[np.ndarray]: + """ + Args: + mask: (h, w) 0~255 + + Returns: + + """ + _, thresh = cv2.threshold(mask, 127, 255, 0) + contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) + + max_area = 0 + max_index = -1 + for i, cnt in enumerate(contours): + area = cv2.contourArea(cnt) + if area > max_area: + max_area = area + max_index = i + + if max_index != -1: + new_mask = np.zeros_like(mask) + return cv2.drawContours(new_mask, contours, max_index, 255, -1) + else: + return mask + + +def is_mac(): + return sys.platform == "darwin" + + +def get_image_ext(img_bytes): + w = imghdr.what("", img_bytes) + if w is None: + w = "jpeg" + return w + + +def decode_base64_to_image( + encoding: str, gray=False +) -> Tuple[np.array, Optional[np.array], Dict]: + if encoding.startswith("data:image/") or encoding.startswith( + "data:application/octet-stream;base64," + ): + encoding = encoding.split(";")[1].split(",")[1] + image = Image.open(io.BytesIO(base64.b64decode(encoding))) + + alpha_channel = None + try: + image = ImageOps.exif_transpose(image) + except: + pass + # exif_transpose will remove exif rotate info,we must call image.info after exif_transpose + infos = image.info + + if gray: + image = image.convert("L") + np_img = np.array(image) + else: + if image.mode == "RGBA": + np_img = np.array(image) + alpha_channel = np_img[:, :, -1] + np_img = cv2.cvtColor(np_img, cv2.COLOR_RGBA2RGB) + else: + image = image.convert("RGB") + np_img = np.array(image) + + return np_img, alpha_channel, infos + + +def encode_pil_to_base64(image: Image, quality: int, infos: Dict) -> bytes: + img_bytes = pil_to_bytes( + image, + "png", + quality=quality, + infos=infos, + ) + return base64.b64encode(img_bytes) + + +def concat_alpha_channel(rgb_np_img, alpha_channel) -> np.ndarray: + if alpha_channel is not None: + if alpha_channel.shape[:2] != rgb_np_img.shape[:2]: + alpha_channel = cv2.resize( + alpha_channel, dsize=(rgb_np_img.shape[1], rgb_np_img.shape[0]) + ) + rgb_np_img = np.concatenate( + (rgb_np_img, alpha_channel[:, :, np.newaxis]), axis=-1 + ) + return rgb_np_img + + +def adjust_mask(mask: np.ndarray, kernel_size: int, operate): + # fronted brush color "ffcc00bb" + # kernel_size = kernel_size*2+1 + mask[mask >= 127] = 255 + mask[mask < 127] = 0 + + if operate == "reverse": + mask = 255 - mask + else: + kernel = cv2.getStructuringElement( + cv2.MORPH_ELLIPSE, (2 * kernel_size + 1, 2 * kernel_size + 1) + ) + if operate == "expand": + mask = cv2.dilate( + mask, + kernel, + iterations=1, + ) + else: + mask = cv2.erode( + mask, + kernel, + iterations=1, + ) + res_mask = np.zeros((mask.shape[0], mask.shape[1], 4), dtype=np.uint8) + res_mask[mask > 128] = [255, 203, 0, int(255 * 0.73)] + res_mask = cv2.cvtColor(res_mask, cv2.COLOR_BGRA2RGBA) + return res_mask + + +def gen_frontend_mask(bgr_or_gray_mask): + if len(bgr_or_gray_mask.shape) == 3 and bgr_or_gray_mask.shape[2] != 1: + bgr_or_gray_mask = cv2.cvtColor(bgr_or_gray_mask, cv2.COLOR_BGR2GRAY) + + # fronted brush color "ffcc00bb" + # TODO: how to set kernel size? + kernel_size = 9 + bgr_or_gray_mask = cv2.dilate( + bgr_or_gray_mask, + np.ones((kernel_size, kernel_size), np.uint8), + iterations=1, + ) + res_mask = np.zeros( + (bgr_or_gray_mask.shape[0], bgr_or_gray_mask.shape[1], 4), dtype=np.uint8 + ) + res_mask[bgr_or_gray_mask > 128] = [255, 203, 0, int(255 * 0.73)] + res_mask = cv2.cvtColor(res_mask, cv2.COLOR_BGRA2RGBA) + return res_mask diff --git a/py/iopaint/installer.py b/py/iopaint/installer.py new file mode 100644 index 0000000..f255e33 --- /dev/null +++ b/py/iopaint/installer.py @@ -0,0 +1,12 @@ +import subprocess +import sys + + +def install(package): + subprocess.check_call([sys.executable, "-m", "pip", "install", package]) + + +def install_plugins_package(): + install("rembg") + install("realesrgan") + install("gfpgan") diff --git a/py/iopaint/model/__init__.py b/py/iopaint/model/__init__.py new file mode 100644 index 0000000..799e2ec --- /dev/null +++ b/py/iopaint/model/__init__.py @@ -0,0 +1,37 @@ +from .anytext.anytext_model import AnyText +from .controlnet import ControlNet +from .fcf import FcF +from .instruct_pix2pix import InstructPix2Pix +from .kandinsky import Kandinsky22 +from .lama import LaMa +from .ldm import LDM +from .manga import Manga +from .mat import MAT +from .mi_gan import MIGAN +from .opencv2 import OpenCV2 +from .paint_by_example import PaintByExample +from .power_paint.power_paint import PowerPaint +from .sd import SD15, SD2, Anything4, RealisticVision14, SD +from .sdxl import SDXL +from .zits import ZITS + +models = { + LaMa.name: LaMa, + LDM.name: LDM, + ZITS.name: ZITS, + MAT.name: MAT, + FcF.name: FcF, + OpenCV2.name: OpenCV2, + Manga.name: Manga, + MIGAN.name: MIGAN, + SD15.name: SD15, + Anything4.name: Anything4, + RealisticVision14.name: RealisticVision14, + SD2.name: SD2, + PaintByExample.name: PaintByExample, + InstructPix2Pix.name: InstructPix2Pix, + Kandinsky22.name: Kandinsky22, + SDXL.name: SDXL, + PowerPaint.name: PowerPaint, + AnyText.name: AnyText, +} diff --git a/py/iopaint/model/anytext/__init__.py b/py/iopaint/model/anytext/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/anytext_model.py b/py/iopaint/model/anytext/anytext_model.py new file mode 100644 index 0000000..097ce5c --- /dev/null +++ b/py/iopaint/model/anytext/anytext_model.py @@ -0,0 +1,73 @@ +import torch +from huggingface_hub import hf_hub_download + +from ...const import ANYTEXT_NAME +from ...model.anytext.anytext_pipeline import AnyTextPipeline +from ...model.base import DiffusionInpaintModel +from ...model.utils import get_torch_dtype, is_local_files_only +from ...schema import InpaintRequest + + +class AnyText(DiffusionInpaintModel): + name = ANYTEXT_NAME + pad_mod = 64 + is_erase_model = False + + @staticmethod + def download(local_files_only=False): + hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="model_index.json", + local_files_only=local_files_only, + ) + ckpt_path = hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="pytorch_model.fp16.safetensors", + local_files_only=local_files_only, + ) + font_path = hf_hub_download( + repo_id=ANYTEXT_NAME, + filename="SourceHanSansSC-Medium.otf", + local_files_only=local_files_only, + ) + return ckpt_path, font_path + + def init_model(self, device, **kwargs): + local_files_only = is_local_files_only(**kwargs) + ckpt_path, font_path = self.download(local_files_only) + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + self.model = AnyTextPipeline( + ckpt_path=ckpt_path, + font_path=font_path, + device=device, + use_fp16=torch_dtype == torch.float16, + ) + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to inpainting + return: BGR IMAGE + """ + height, width = image.shape[:2] + mask = mask.astype("float32") / 255.0 + masked_image = image * (1 - mask) + + # list of rgb ndarray + results, rtn_code, rtn_warning = self.model( + image=image, + masked_image=masked_image, + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + height=height, + width=width, + seed=config.sd_seed, + sort_priority="y", + callback=self.callback + ) + inpainted_rgb_image = results[0][..., ::-1] + return inpainted_rgb_image diff --git a/py/iopaint/model/anytext/anytext_pipeline.py b/py/iopaint/model/anytext/anytext_pipeline.py new file mode 100644 index 0000000..445f943 --- /dev/null +++ b/py/iopaint/model/anytext/anytext_pipeline.py @@ -0,0 +1,403 @@ +""" +AnyText: Multilingual Visual Text Generation And Editing +Paper: https://arxiv.org/abs/2311.03054 +Code: https://github.com/tyxsspa/AnyText +Copyright (c) Alibaba, Inc. and its affiliates. +""" +import os +from pathlib import Path + +from ...model.utils import set_seed +from safetensors.torch import load_file + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" +import torch +import re +import numpy as np +import cv2 +import einops +from PIL import ImageFont +from ...model.anytext.cldm.model import create_model, load_state_dict +from ...model.anytext.cldm.ddim_hacked import DDIMSampler +from ...model.anytext.utils import ( + check_channels, + draw_glyph, + draw_glyph2, +) + + +BBOX_MAX_NUM = 8 +PLACE_HOLDER = "*" +max_chars = 20 + +ANYTEXT_CFG = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "anytext_sd15.yaml" +) + + +def check_limits(tensor): + float16_min = torch.finfo(torch.float16).min + float16_max = torch.finfo(torch.float16).max + + # 检查张量中是否有值小于float16的最小值或大于float16的最大值 + is_below_min = (tensor < float16_min).any() + is_above_max = (tensor > float16_max).any() + + return is_below_min or is_above_max + + +class AnyTextPipeline: + def __init__(self, ckpt_path, font_path, device, use_fp16=True): + self.cfg_path = ANYTEXT_CFG + self.font_path = font_path + self.use_fp16 = use_fp16 + self.device = device + + self.font = ImageFont.truetype(font_path, size=60) + self.model = create_model( + self.cfg_path, + device=self.device, + use_fp16=self.use_fp16, + ) + if self.use_fp16: + self.model = self.model.half() + if Path(ckpt_path).suffix == ".safetensors": + state_dict = load_file(ckpt_path, device="cpu") + else: + state_dict = load_state_dict(ckpt_path, location="cpu") + self.model.load_state_dict(state_dict, strict=False) + self.model = self.model.eval().to(self.device) + self.ddim_sampler = DDIMSampler(self.model, device=self.device) + + def __call__( + self, + prompt: str, + negative_prompt: str, + image: np.ndarray, + masked_image: np.ndarray, + num_inference_steps: int, + strength: float, + guidance_scale: float, + height: int, + width: int, + seed: int, + sort_priority: str = "y", + callback=None, + ): + """ + + Args: + prompt: + negative_prompt: + image: + masked_image: + num_inference_steps: + strength: + guidance_scale: + height: + width: + seed: + sort_priority: x: left-right, y: top-down + + Returns: + result: list of images in numpy.ndarray format + rst_code: 0: normal -1: error 1:warning + rst_info: string of error or warning + + """ + set_seed(seed) + str_warning = "" + + mode = "text-editing" + revise_pos = False + img_count = 1 + ddim_steps = num_inference_steps + w = width + h = height + strength = strength + cfg_scale = guidance_scale + eta = 0.0 + + prompt, texts = self.modify_prompt(prompt) + if prompt is None and texts is None: + return ( + None, + -1, + "You have input Chinese prompt but the translator is not loaded!", + "", + ) + n_lines = len(texts) + if mode in ["text-generation", "gen"]: + edit_image = np.ones((h, w, 3)) * 127.5 # empty mask image + elif mode in ["text-editing", "edit"]: + if masked_image is None or image is None: + return ( + None, + -1, + "Reference image and position image are needed for text editing!", + "", + ) + if isinstance(image, str): + image = cv2.imread(image)[..., ::-1] + assert image is not None, f"Can't read ori_image image from{image}!" + elif isinstance(image, torch.Tensor): + image = image.cpu().numpy() + else: + assert isinstance( + image, np.ndarray + ), f"Unknown format of ori_image: {type(image)}" + edit_image = image.clip(1, 255) # for mask reason + edit_image = check_channels(edit_image) + # edit_image = resize_image( + # edit_image, max_length=768 + # ) # make w h multiple of 64, resize if w or h > max_length + h, w = edit_image.shape[:2] # change h, w by input ref_img + # preprocess pos_imgs(if numpy, make sure it's white pos in black bg) + if masked_image is None: + pos_imgs = np.zeros((w, h, 1)) + if isinstance(masked_image, str): + masked_image = cv2.imread(masked_image)[..., ::-1] + assert ( + masked_image is not None + ), f"Can't read draw_pos image from{masked_image}!" + pos_imgs = 255 - masked_image + elif isinstance(masked_image, torch.Tensor): + pos_imgs = masked_image.cpu().numpy() + else: + assert isinstance( + masked_image, np.ndarray + ), f"Unknown format of draw_pos: {type(masked_image)}" + pos_imgs = 255 - masked_image + pos_imgs = pos_imgs[..., 0:1] + pos_imgs = cv2.convertScaleAbs(pos_imgs) + _, pos_imgs = cv2.threshold(pos_imgs, 254, 255, cv2.THRESH_BINARY) + # seprate pos_imgs + pos_imgs = self.separate_pos_imgs(pos_imgs, sort_priority) + if len(pos_imgs) == 0: + pos_imgs = [np.zeros((h, w, 1))] + if len(pos_imgs) < n_lines: + if n_lines == 1 and texts[0] == " ": + pass # text-to-image without text + else: + raise RuntimeError( + f"{n_lines} text line to draw from prompt, not enough mask area({len(pos_imgs)}) on images" + ) + elif len(pos_imgs) > n_lines: + str_warning = f"Warning: found {len(pos_imgs)} positions that > needed {n_lines} from prompt." + # get pre_pos, poly_list, hint that needed for anytext + pre_pos = [] + poly_list = [] + for input_pos in pos_imgs: + if input_pos.mean() != 0: + input_pos = ( + input_pos[..., np.newaxis] + if len(input_pos.shape) == 2 + else input_pos + ) + poly, pos_img = self.find_polygon(input_pos) + pre_pos += [pos_img / 255.0] + poly_list += [poly] + else: + pre_pos += [np.zeros((h, w, 1))] + poly_list += [None] + np_hint = np.sum(pre_pos, axis=0).clip(0, 1) + # prepare info dict + info = {} + info["glyphs"] = [] + info["gly_line"] = [] + info["positions"] = [] + info["n_lines"] = [len(texts)] * img_count + gly_pos_imgs = [] + for i in range(len(texts)): + text = texts[i] + if len(text) > max_chars: + str_warning = ( + f'"{text}" length > max_chars: {max_chars}, will be cut off...' + ) + text = text[:max_chars] + gly_scale = 2 + if pre_pos[i].mean() != 0: + gly_line = draw_glyph(self.font, text) + glyphs = draw_glyph2( + self.font, + text, + poly_list[i], + scale=gly_scale, + width=w, + height=h, + add_space=False, + ) + gly_pos_img = cv2.drawContours( + glyphs * 255, [poly_list[i] * gly_scale], 0, (255, 255, 255), 1 + ) + if revise_pos: + resize_gly = cv2.resize( + glyphs, (pre_pos[i].shape[1], pre_pos[i].shape[0]) + ) + new_pos = cv2.morphologyEx( + (resize_gly * 255).astype(np.uint8), + cv2.MORPH_CLOSE, + kernel=np.ones( + (resize_gly.shape[0] // 10, resize_gly.shape[1] // 10), + dtype=np.uint8, + ), + iterations=1, + ) + new_pos = ( + new_pos[..., np.newaxis] if len(new_pos.shape) == 2 else new_pos + ) + contours, _ = cv2.findContours( + new_pos, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE + ) + if len(contours) != 1: + str_warning = f"Fail to revise position {i} to bounding rect, remain position unchanged..." + else: + rect = cv2.minAreaRect(contours[0]) + poly = np.int0(cv2.boxPoints(rect)) + pre_pos[i] = ( + cv2.drawContours(new_pos, [poly], -1, 255, -1) / 255.0 + ) + gly_pos_img = cv2.drawContours( + glyphs * 255, [poly * gly_scale], 0, (255, 255, 255), 1 + ) + gly_pos_imgs += [gly_pos_img] # for show + else: + glyphs = np.zeros((h * gly_scale, w * gly_scale, 1)) + gly_line = np.zeros((80, 512, 1)) + gly_pos_imgs += [ + np.zeros((h * gly_scale, w * gly_scale, 1)) + ] # for show + pos = pre_pos[i] + info["glyphs"] += [self.arr2tensor(glyphs, img_count)] + info["gly_line"] += [self.arr2tensor(gly_line, img_count)] + info["positions"] += [self.arr2tensor(pos, img_count)] + # get masked_x + masked_img = ((edit_image.astype(np.float32) / 127.5) - 1.0) * (1 - np_hint) + masked_img = np.transpose(masked_img, (2, 0, 1)) + masked_img = torch.from_numpy(masked_img.copy()).float().to(self.device) + if self.use_fp16: + masked_img = masked_img.half() + encoder_posterior = self.model.encode_first_stage(masked_img[None, ...]) + masked_x = self.model.get_first_stage_encoding(encoder_posterior).detach() + if self.use_fp16: + masked_x = masked_x.half() + info["masked_x"] = torch.cat([masked_x for _ in range(img_count)], dim=0) + + hint = self.arr2tensor(np_hint, img_count) + cond = self.model.get_learned_conditioning( + dict( + c_concat=[hint], + c_crossattn=[[prompt] * img_count], + text_info=info, + ) + ) + un_cond = self.model.get_learned_conditioning( + dict( + c_concat=[hint], + c_crossattn=[[negative_prompt] * img_count], + text_info=info, + ) + ) + shape = (4, h // 8, w // 8) + self.model.control_scales = [strength] * 13 + samples, intermediates = self.ddim_sampler.sample( + ddim_steps, + img_count, + shape, + cond, + verbose=False, + eta=eta, + unconditional_guidance_scale=cfg_scale, + unconditional_conditioning=un_cond, + callback=callback + ) + if self.use_fp16: + samples = samples.half() + x_samples = self.model.decode_first_stage(samples) + x_samples = ( + (einops.rearrange(x_samples, "b c h w -> b h w c") * 127.5 + 127.5) + .cpu() + .numpy() + .clip(0, 255) + .astype(np.uint8) + ) + results = [x_samples[i] for i in range(img_count)] + # if ( + # mode == "edit" and False + # ): # replace backgound in text editing but not ideal yet + # results = [r * np_hint + edit_image * (1 - np_hint) for r in results] + # results = [r.clip(0, 255).astype(np.uint8) for r in results] + # if len(gly_pos_imgs) > 0 and show_debug: + # glyph_bs = np.stack(gly_pos_imgs, axis=2) + # glyph_img = np.sum(glyph_bs, axis=2) * 255 + # glyph_img = glyph_img.clip(0, 255).astype(np.uint8) + # results += [np.repeat(glyph_img, 3, axis=2)] + rst_code = 1 if str_warning else 0 + return results, rst_code, str_warning + + def modify_prompt(self, prompt): + prompt = prompt.replace("“", '"') + prompt = prompt.replace("”", '"') + p = '"(.*?)"' + strs = re.findall(p, prompt) + if len(strs) == 0: + strs = [" "] + else: + for s in strs: + prompt = prompt.replace(f'"{s}"', f" {PLACE_HOLDER} ", 1) + # if self.is_chinese(prompt): + # if self.trans_pipe is None: + # return None, None + # old_prompt = prompt + # prompt = self.trans_pipe(input=prompt + " .")["translation"][:-1] + # print(f"Translate: {old_prompt} --> {prompt}") + return prompt, strs + + # def is_chinese(self, text): + # text = checker._clean_text(text) + # for char in text: + # cp = ord(char) + # if checker._is_chinese_char(cp): + # return True + # return False + + def separate_pos_imgs(self, img, sort_priority, gap=102): + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(img) + components = [] + for label in range(1, num_labels): + component = np.zeros_like(img) + component[labels == label] = 255 + components.append((component, centroids[label])) + if sort_priority == "y": + fir, sec = 1, 0 # top-down first + elif sort_priority == "x": + fir, sec = 0, 1 # left-right first + components.sort(key=lambda c: (c[1][fir] // gap, c[1][sec] // gap)) + sorted_components = [c[0] for c in components] + return sorted_components + + def find_polygon(self, image, min_rect=False): + contours, hierarchy = cv2.findContours( + image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE + ) + max_contour = max(contours, key=cv2.contourArea) # get contour with max area + if min_rect: + # get minimum enclosing rectangle + rect = cv2.minAreaRect(max_contour) + poly = np.int0(cv2.boxPoints(rect)) + else: + # get approximate polygon + epsilon = 0.01 * cv2.arcLength(max_contour, True) + poly = cv2.approxPolyDP(max_contour, epsilon, True) + n, _, xy = poly.shape + poly = poly.reshape(n, xy) + cv2.drawContours(image, [poly], -1, 255, -1) + return poly, image + + def arr2tensor(self, arr, bs): + arr = np.transpose(arr, (2, 0, 1)) + _arr = torch.from_numpy(arr.copy()).float().to(self.device) + if self.use_fp16: + _arr = _arr.half() + _arr = torch.stack([_arr for _ in range(bs)], dim=0) + return _arr diff --git a/py/iopaint/model/anytext/anytext_sd15.yaml b/py/iopaint/model/anytext/anytext_sd15.yaml new file mode 100644 index 0000000..d727594 --- /dev/null +++ b/py/iopaint/model/anytext/anytext_sd15.yaml @@ -0,0 +1,99 @@ +model: + target: iopaint.model.anytext.cldm.cldm.ControlLDM + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "img" + cond_stage_key: "caption" + control_key: "hint" + glyph_key: "glyphs" + position_key: "positions" + image_size: 64 + channels: 4 + cond_stage_trainable: true # need be true when embedding_manager is valid + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False + only_mid_control: False + loss_alpha: 0 # perceptual loss, 0.003 + loss_beta: 0 # ctc loss + latin_weight: 1.0 # latin text line may need smaller weigth + with_step_weight: true + use_vae_upsample: true + embedding_manager_config: + target: iopaint.model.anytext.cldm.embedding_manager.EmbeddingManager + params: + valid: true # v6 + emb_type: ocr # ocr, vit, conv + glyph_channels: 1 + position_channels: 1 + add_pos: false + placeholder_string: '*' + + control_stage_config: + target: iopaint.model.anytext.cldm.cldm.ControlNet + params: + image_size: 32 # unused + in_channels: 4 + model_channels: 320 + glyph_channels: 1 + position_channels: 1 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + unet_config: + target: iopaint.model.anytext.cldm.cldm.ControlledUnetModel + params: + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: iopaint.model.anytext.ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedderT3 + params: + version: openai/clip-vit-large-patch14 + use_vision: false # v6 diff --git a/py/iopaint/model/anytext/cldm/__init__.py b/py/iopaint/model/anytext/cldm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/cldm/cldm.py b/py/iopaint/model/anytext/cldm/cldm.py new file mode 100644 index 0000000..ad9692a --- /dev/null +++ b/py/iopaint/model/anytext/cldm/cldm.py @@ -0,0 +1,630 @@ +import os +from pathlib import Path + +import einops +import torch +import torch as th +import torch.nn as nn +import copy +from easydict import EasyDict as edict + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + conv_nd, + linear, + zero_module, + timestep_embedding, +) + +from einops import rearrange, repeat +from iopaint.model.anytext.ldm.modules.attention import SpatialTransformer +from iopaint.model.anytext.ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock +from iopaint.model.anytext.ldm.models.diffusion.ddpm import LatentDiffusion +from iopaint.model.anytext.ldm.util import log_txt_as_img, exists, instantiate_from_config +from iopaint.model.anytext.ldm.models.diffusion.ddim import DDIMSampler +from iopaint.model.anytext.ldm.modules.distributions.distributions import DiagonalGaussianDistribution +from .recognizer import TextRecognizer, create_predictor + +CURRENT_DIR = Path(os.path.dirname(os.path.abspath(__file__))) + + +def count_parameters(model): + return sum(p.numel() for p in model.parameters() if p.requires_grad) + + +class ControlledUnetModel(UNetModel): + def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs): + hs = [] + with torch.no_grad(): + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + if self.use_fp16: + t_emb = t_emb.half() + emb = self.time_embed(t_emb) + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb, context) + hs.append(h) + h = self.middle_block(h, emb, context) + + if control is not None: + h += control.pop() + + for i, module in enumerate(self.output_blocks): + if only_mid_control or control is None: + h = torch.cat([h, hs.pop()], dim=1) + else: + h = torch.cat([h, hs.pop() + control.pop()], dim=1) + h = module(h, emb, context) + + h = h.type(x.dtype) + return self.out(h) + + +class ControlNet(nn.Module): + def __init__( + self, + image_size, + in_channels, + model_channels, + glyph_channels, + position_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + use_checkpoint=False, + use_fp16=False, + num_heads=-1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + use_spatial_transformer=False, # custom transformer support + transformer_depth=1, # custom transformer support + context_dim=None, # custom transformer support + n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model + legacy=True, + disable_self_attentions=None, + num_attention_blocks=None, + disable_middle_self_attn=False, + use_linear_in_transformer=False, + ): + super().__init__() + if use_spatial_transformer: + assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' + + if context_dim is not None: + assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' + from omegaconf.listconfig import ListConfig + if type(context_dim) == ListConfig: + context_dim = list(context_dim) + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + if num_heads == -1: + assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' + + if num_head_channels == -1: + assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' + self.dims = dims + self.image_size = image_size + self.in_channels = in_channels + self.model_channels = model_channels + if isinstance(num_res_blocks, int): + self.num_res_blocks = len(channel_mult) * [num_res_blocks] + else: + if len(num_res_blocks) != len(channel_mult): + raise ValueError("provide num_res_blocks either as an int (globally constant) or " + "as a list/tuple (per-level) with the same length as channel_mult") + self.num_res_blocks = num_res_blocks + if disable_self_attentions is not None: + # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not + assert len(disable_self_attentions) == len(channel_mult) + if num_attention_blocks is not None: + assert len(num_attention_blocks) == len(self.num_res_blocks) + assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) + print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " + f"This option has LESS priority than attention_resolutions {attention_resolutions}, " + f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " + f"attention will still not be set.") + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.use_checkpoint = use_checkpoint + self.use_fp16 = use_fp16 + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + self.predict_codebook_ids = n_embed is not None + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + self.input_blocks = nn.ModuleList( + [ + TimestepEmbedSequential( + conv_nd(dims, in_channels, model_channels, 3, padding=1) + ) + ] + ) + self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)]) + + self.glyph_block = TimestepEmbedSequential( + conv_nd(dims, glyph_channels, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 16, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 16, 16, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 16, 32, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 32, 32, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 32, 96, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 96, 96, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 96, 256, 3, padding=1, stride=2), + nn.SiLU(), + ) + + self.position_block = TimestepEmbedSequential( + conv_nd(dims, position_channels, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 8, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 8, 16, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 16, 16, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 16, 32, 3, padding=1, stride=2), + nn.SiLU(), + conv_nd(dims, 32, 32, 3, padding=1), + nn.SiLU(), + conv_nd(dims, 32, 64, 3, padding=1, stride=2), + nn.SiLU(), + ) + + self.fuse_block = zero_module(conv_nd(dims, 256+64+4, model_channels, 3, padding=1)) + + self._feature_size = model_channels + input_block_chans = [model_channels] + ch = model_channels + ds = 1 + for level, mult in enumerate(channel_mult): + for nr in range(self.num_res_blocks[level]): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=mult * model_channels, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = mult * model_channels + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + # num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self.zero_convs.append(self.make_zero_conv(ch)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample( + ch, conv_resample, dims=dims, out_channels=out_ch + ) + ) + ) + ch = out_ch + input_block_chans.append(ch) + self.zero_convs.append(self.make_zero_conv(ch)) + ds *= 2 + self._feature_size += ch + + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + # num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self.middle_block_out = self.make_zero_conv(ch) + self._feature_size += ch + + def make_zero_conv(self, channels): + return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0))) + + def forward(self, x, hint, text_info, timesteps, context, **kwargs): + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + if self.use_fp16: + t_emb = t_emb.half() + emb = self.time_embed(t_emb) + + # guided_hint from text_info + B, C, H, W = x.shape + glyphs = torch.cat(text_info['glyphs'], dim=1).sum(dim=1, keepdim=True) + positions = torch.cat(text_info['positions'], dim=1).sum(dim=1, keepdim=True) + enc_glyph = self.glyph_block(glyphs, emb, context) + enc_pos = self.position_block(positions, emb, context) + guided_hint = self.fuse_block(torch.cat([enc_glyph, enc_pos, text_info['masked_x']], dim=1)) + + outs = [] + + h = x.type(self.dtype) + for module, zero_conv in zip(self.input_blocks, self.zero_convs): + if guided_hint is not None: + h = module(h, emb, context) + h += guided_hint + guided_hint = None + else: + h = module(h, emb, context) + outs.append(zero_conv(h, emb, context)) + + h = self.middle_block(h, emb, context) + outs.append(self.middle_block_out(h, emb, context)) + + return outs + + +class ControlLDM(LatentDiffusion): + + def __init__(self, control_stage_config, control_key, glyph_key, position_key, only_mid_control, loss_alpha=0, loss_beta=0, with_step_weight=False, use_vae_upsample=False, latin_weight=1.0, embedding_manager_config=None, *args, **kwargs): + self.use_fp16 = kwargs.pop('use_fp16', False) + super().__init__(*args, **kwargs) + self.control_model = instantiate_from_config(control_stage_config) + self.control_key = control_key + self.glyph_key = glyph_key + self.position_key = position_key + self.only_mid_control = only_mid_control + self.control_scales = [1.0] * 13 + self.loss_alpha = loss_alpha + self.loss_beta = loss_beta + self.with_step_weight = with_step_weight + self.use_vae_upsample = use_vae_upsample + self.latin_weight = latin_weight + + if embedding_manager_config is not None and embedding_manager_config.params.valid: + self.embedding_manager = self.instantiate_embedding_manager(embedding_manager_config, self.cond_stage_model) + for param in self.embedding_manager.embedding_parameters(): + param.requires_grad = True + else: + self.embedding_manager = None + if self.loss_alpha > 0 or self.loss_beta > 0 or self.embedding_manager: + if embedding_manager_config.params.emb_type == 'ocr': + self.text_predictor = create_predictor().eval() + args = edict() + args.rec_image_shape = "3, 48, 320" + args.rec_batch_num = 6 + args.rec_char_dict_path = str(CURRENT_DIR.parent / "ocr_recog" / "ppocr_keys_v1.txt") + args.use_fp16 = self.use_fp16 + self.cn_recognizer = TextRecognizer(args, self.text_predictor) + for param in self.text_predictor.parameters(): + param.requires_grad = False + if self.embedding_manager: + self.embedding_manager.recog = self.cn_recognizer + + @torch.no_grad() + def get_input(self, batch, k, bs=None, *args, **kwargs): + if self.embedding_manager is None: # fill in full caption + self.fill_caption(batch) + x, c, mx = super().get_input(batch, self.first_stage_key, mask_k='masked_img', *args, **kwargs) + control = batch[self.control_key] # for log_images and loss_alpha, not real control + if bs is not None: + control = control[:bs] + control = control.to(self.device) + control = einops.rearrange(control, 'b h w c -> b c h w') + control = control.to(memory_format=torch.contiguous_format).float() + + inv_mask = batch['inv_mask'] + if bs is not None: + inv_mask = inv_mask[:bs] + inv_mask = inv_mask.to(self.device) + inv_mask = einops.rearrange(inv_mask, 'b h w c -> b c h w') + inv_mask = inv_mask.to(memory_format=torch.contiguous_format).float() + + glyphs = batch[self.glyph_key] + gly_line = batch['gly_line'] + positions = batch[self.position_key] + n_lines = batch['n_lines'] + language = batch['language'] + texts = batch['texts'] + assert len(glyphs) == len(positions) + for i in range(len(glyphs)): + if bs is not None: + glyphs[i] = glyphs[i][:bs] + gly_line[i] = gly_line[i][:bs] + positions[i] = positions[i][:bs] + n_lines = n_lines[:bs] + glyphs[i] = glyphs[i].to(self.device) + gly_line[i] = gly_line[i].to(self.device) + positions[i] = positions[i].to(self.device) + glyphs[i] = einops.rearrange(glyphs[i], 'b h w c -> b c h w') + gly_line[i] = einops.rearrange(gly_line[i], 'b h w c -> b c h w') + positions[i] = einops.rearrange(positions[i], 'b h w c -> b c h w') + glyphs[i] = glyphs[i].to(memory_format=torch.contiguous_format).float() + gly_line[i] = gly_line[i].to(memory_format=torch.contiguous_format).float() + positions[i] = positions[i].to(memory_format=torch.contiguous_format).float() + info = {} + info['glyphs'] = glyphs + info['positions'] = positions + info['n_lines'] = n_lines + info['language'] = language + info['texts'] = texts + info['img'] = batch['img'] # nhwc, (-1,1) + info['masked_x'] = mx + info['gly_line'] = gly_line + info['inv_mask'] = inv_mask + return x, dict(c_crossattn=[c], c_concat=[control], text_info=info) + + def apply_model(self, x_noisy, t, cond, *args, **kwargs): + assert isinstance(cond, dict) + diffusion_model = self.model.diffusion_model + _cond = torch.cat(cond['c_crossattn'], 1) + _hint = torch.cat(cond['c_concat'], 1) + if self.use_fp16: + x_noisy = x_noisy.half() + control = self.control_model(x=x_noisy, timesteps=t, context=_cond, hint=_hint, text_info=cond['text_info']) + control = [c * scale for c, scale in zip(control, self.control_scales)] + eps = diffusion_model(x=x_noisy, timesteps=t, context=_cond, control=control, only_mid_control=self.only_mid_control) + + return eps + + def instantiate_embedding_manager(self, config, embedder): + model = instantiate_from_config(config, embedder=embedder) + return model + + @torch.no_grad() + def get_unconditional_conditioning(self, N): + return self.get_learned_conditioning(dict(c_crossattn=[[""] * N], text_info=None)) + + def get_learned_conditioning(self, c): + if self.cond_stage_forward is None: + if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode): + if self.embedding_manager is not None and c['text_info'] is not None: + self.embedding_manager.encode_text(c['text_info']) + if isinstance(c, dict): + cond_txt = c['c_crossattn'][0] + else: + cond_txt = c + if self.embedding_manager is not None: + cond_txt = self.cond_stage_model.encode(cond_txt, embedding_manager=self.embedding_manager) + else: + cond_txt = self.cond_stage_model.encode(cond_txt) + if isinstance(c, dict): + c['c_crossattn'][0] = cond_txt + else: + c = cond_txt + if isinstance(c, DiagonalGaussianDistribution): + c = c.mode() + else: + c = self.cond_stage_model(c) + else: + assert hasattr(self.cond_stage_model, self.cond_stage_forward) + c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) + return c + + def fill_caption(self, batch, place_holder='*'): + bs = len(batch['n_lines']) + cond_list = copy.deepcopy(batch[self.cond_stage_key]) + for i in range(bs): + n_lines = batch['n_lines'][i] + if n_lines == 0: + continue + cur_cap = cond_list[i] + for j in range(n_lines): + r_txt = batch['texts'][j][i] + cur_cap = cur_cap.replace(place_holder, f'"{r_txt}"', 1) + cond_list[i] = cur_cap + batch[self.cond_stage_key] = cond_list + + @torch.no_grad() + def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None, + quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True, + plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs): + use_ddim = ddim_steps is not None + + log = dict() + z, c = self.get_input(batch, self.first_stage_key, bs=N) + if self.cond_stage_trainable: + with torch.no_grad(): + c = self.get_learned_conditioning(c) + c_crossattn = c["c_crossattn"][0][:N] + c_cat = c["c_concat"][0][:N] + text_info = c["text_info"] + text_info['glyphs'] = [i[:N] for i in text_info['glyphs']] + text_info['gly_line'] = [i[:N] for i in text_info['gly_line']] + text_info['positions'] = [i[:N] for i in text_info['positions']] + text_info['n_lines'] = text_info['n_lines'][:N] + text_info['masked_x'] = text_info['masked_x'][:N] + text_info['img'] = text_info['img'][:N] + + N = min(z.shape[0], N) + n_row = min(z.shape[0], n_row) + log["reconstruction"] = self.decode_first_stage(z) + log["masked_image"] = self.decode_first_stage(text_info['masked_x']) + log["control"] = c_cat * 2.0 - 1.0 + log["img"] = text_info['img'].permute(0, 3, 1, 2) # log source image if needed + # get glyph + glyph_bs = torch.stack(text_info['glyphs']) + glyph_bs = torch.sum(glyph_bs, dim=0) * 2.0 - 1.0 + log["glyph"] = torch.nn.functional.interpolate(glyph_bs, size=(512, 512), mode='bilinear', align_corners=True,) + # fill caption + if not self.embedding_manager: + self.fill_caption(batch) + captions = batch[self.cond_stage_key] + log["conditioning"] = log_txt_as_img((512, 512), captions, size=16) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), '1 -> b', b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w') + diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w') + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], "text_info": text_info}, + batch_size=N, ddim=use_ddim, + ddim_steps=ddim_steps, eta=ddim_eta) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_cross = self.get_unconditional_conditioning(N) + uc_cat = c_cat # torch.zeros_like(c_cat) + uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross['c_crossattn'][0]], "text_info": text_info} + samples_cfg, tmps = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c_crossattn], "text_info": text_info}, + batch_size=N, ddim=use_ddim, + ddim_steps=ddim_steps, eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc_full, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg + pred_x0 = False # wether log pred_x0 + if pred_x0: + for idx in range(len(tmps['pred_x0'])): + pred_x0 = self.decode_first_stage(tmps['pred_x0'][idx]) + log[f"pred_x0_{tmps['index'][idx]}"] = pred_x0 + + return log + + @torch.no_grad() + def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): + ddim_sampler = DDIMSampler(self) + b, c, h, w = cond["c_concat"][0].shape + shape = (self.channels, h // 8, w // 8) + samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, log_every_t=5, **kwargs) + return samples, intermediates + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.control_model.parameters()) + if self.embedding_manager: + params += list(self.embedding_manager.embedding_parameters()) + if not self.sd_locked: + # params += list(self.model.diffusion_model.input_blocks.parameters()) + # params += list(self.model.diffusion_model.middle_block.parameters()) + params += list(self.model.diffusion_model.output_blocks.parameters()) + params += list(self.model.diffusion_model.out.parameters()) + if self.unlockKV: + nCount = 0 + for name, param in self.model.diffusion_model.named_parameters(): + if 'attn2.to_k' in name or 'attn2.to_v' in name: + params += [param] + nCount += 1 + print(f'Cross attention is unlocked, and {nCount} Wk or Wv are added to potimizers!!!') + + opt = torch.optim.AdamW(params, lr=lr) + return opt + + def low_vram_shift(self, is_diffusing): + if is_diffusing: + self.model = self.model.cuda() + self.control_model = self.control_model.cuda() + self.first_stage_model = self.first_stage_model.cpu() + self.cond_stage_model = self.cond_stage_model.cpu() + else: + self.model = self.model.cpu() + self.control_model = self.control_model.cpu() + self.first_stage_model = self.first_stage_model.cuda() + self.cond_stage_model = self.cond_stage_model.cuda() diff --git a/py/iopaint/model/anytext/cldm/ddim_hacked.py b/py/iopaint/model/anytext/cldm/ddim_hacked.py new file mode 100644 index 0000000..b23a883 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/ddim_hacked.py @@ -0,0 +1,486 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + make_ddim_sampling_parameters, + make_ddim_timesteps, + noise_like, + extract_into_tensor, +) + + +class DDIMSampler(object): + def __init__(self, model, device, schedule="linear", **kwargs): + super().__init__() + self.device = device + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device(self.device): + attr = attr.to(torch.device(self.device)) + setattr(self, name, attr) + + def make_schedule( + self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True + ): + self.ddim_timesteps = make_ddim_timesteps( + ddim_discr_method=ddim_discretize, + num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps, + verbose=verbose, + ) + alphas_cumprod = self.model.alphas_cumprod + assert ( + alphas_cumprod.shape[0] == self.ddpm_num_timesteps + ), "alphas have to be defined for each timestep" + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.device) + + self.register_buffer("betas", to_torch(self.model.betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer( + "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev) + ) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer( + "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", + to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())), + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", + to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)), + ) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters( + alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, + verbose=verbose, + ) + self.register_buffer("ddim_sigmas", ddim_sigmas) + self.register_buffer("ddim_alphas", ddim_alphas) + self.register_buffer("ddim_alphas_prev", ddim_alphas_prev) + self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) + / (1 - self.alphas_cumprod) + * (1 - self.alphas_cumprod / self.alphas_cumprod_prev) + ) + self.register_buffer( + "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps + ) + + @torch.no_grad() + def sample( + self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0.0, + mask=None, + x0=None, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + ucg_schedule=None, + **kwargs, + ): + if conditioning is not None: + if isinstance(conditioning, dict): + ctmp = conditioning[list(conditioning.keys())[0]] + while isinstance(ctmp, list): + ctmp = ctmp[0] + cbs = ctmp.shape[0] + if cbs != batch_size: + print( + f"Warning: Got {cbs} conditionings but batch-size is {batch_size}" + ) + + elif isinstance(conditioning, list): + for ctmp in conditioning: + if ctmp.shape[0] != batch_size: + print( + f"Warning: Got {cbs} conditionings but batch-size is {batch_size}" + ) + + else: + if conditioning.shape[0] != batch_size: + print( + f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}" + ) + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f"Data shape for DDIM sampling is {size}, eta {eta}") + + samples, intermediates = self.ddim_sampling( + conditioning, + size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, + x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ucg_schedule=ucg_schedule, + ) + return samples, intermediates + + @torch.no_grad() + def ddim_sampling( + self, + cond, + shape, + x_T=None, + ddim_use_original_steps=False, + callback=None, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + img_callback=None, + log_every_t=100, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + dynamic_threshold=None, + ucg_schedule=None, + ): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = ( + self.ddpm_num_timesteps + if ddim_use_original_steps + else self.ddim_timesteps + ) + elif timesteps is not None and not ddim_use_original_steps: + subset_end = ( + int( + min(timesteps / self.ddim_timesteps.shape[0], 1) + * self.ddim_timesteps.shape[0] + ) + - 1 + ) + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {"x_inter": [img], "pred_x0": [img]} + time_range = ( + reversed(range(0, timesteps)) + if ddim_use_original_steps + else np.flip(timesteps) + ) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="DDIM Sampler", total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample( + x0, ts + ) # TODO: deterministic forward pass? + img = img_orig * mask + (1.0 - mask) * img + + if ucg_schedule is not None: + assert len(ucg_schedule) == len(time_range) + unconditional_guidance_scale = ucg_schedule[i] + + outs = self.p_sample_ddim( + img, + cond, + ts, + index=index, + use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, + temperature=temperature, + noise_dropout=noise_dropout, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ) + img, pred_x0 = outs + if callback: + callback(None, i, None, None) + if img_callback: + img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates["x_inter"].append(img) + intermediates["pred_x0"].append(pred_x0) + + return img, intermediates + + @torch.no_grad() + def p_sample_ddim( + self, + x, + c, + t, + index, + repeat_noise=False, + use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + dynamic_threshold=None, + ): + b, *_, device = *x.shape, x.device + + if unconditional_conditioning is None or unconditional_guidance_scale == 1.0: + model_output = self.model.apply_model(x, t, c) + else: + model_t = self.model.apply_model(x, t, c) + model_uncond = self.model.apply_model(x, t, unconditional_conditioning) + model_output = model_uncond + unconditional_guidance_scale * ( + model_t - model_uncond + ) + + if self.model.parameterization == "v": + e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) + else: + e_t = model_output + + if score_corrector is not None: + assert self.model.parameterization == "eps", "not implemented" + e_t = score_corrector.modify_score( + self.model, e_t, x, t, c, **corrector_kwargs + ) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = ( + self.model.alphas_cumprod_prev + if use_original_steps + else self.ddim_alphas_prev + ) + sqrt_one_minus_alphas = ( + self.model.sqrt_one_minus_alphas_cumprod + if use_original_steps + else self.ddim_sqrt_one_minus_alphas + ) + sigmas = ( + self.model.ddim_sigmas_for_original_num_steps + if use_original_steps + else self.ddim_sigmas + ) + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full( + (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device + ) + + # current prediction for x_0 + if self.model.parameterization != "v": + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + else: + pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) + + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + + if dynamic_threshold is not None: + raise NotImplementedError() + + # direction pointing to x_t + dir_xt = (1.0 - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + @torch.no_grad() + def encode( + self, + x0, + c, + t_enc, + use_original_steps=False, + return_intermediates=None, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + callback=None, + ): + timesteps = ( + np.arange(self.ddpm_num_timesteps) + if use_original_steps + else self.ddim_timesteps + ) + num_reference_steps = timesteps.shape[0] + + assert t_enc <= num_reference_steps + num_steps = t_enc + + if use_original_steps: + alphas_next = self.alphas_cumprod[:num_steps] + alphas = self.alphas_cumprod_prev[:num_steps] + else: + alphas_next = self.ddim_alphas[:num_steps] + alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) + + x_next = x0 + intermediates = [] + inter_steps = [] + for i in tqdm(range(num_steps), desc="Encoding Image"): + t = torch.full( + (x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long + ) + if unconditional_guidance_scale == 1.0: + noise_pred = self.model.apply_model(x_next, t, c) + else: + assert unconditional_conditioning is not None + e_t_uncond, noise_pred = torch.chunk( + self.model.apply_model( + torch.cat((x_next, x_next)), + torch.cat((t, t)), + torch.cat((unconditional_conditioning, c)), + ), + 2, + ) + noise_pred = e_t_uncond + unconditional_guidance_scale * ( + noise_pred - e_t_uncond + ) + + xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next + weighted_noise_pred = ( + alphas_next[i].sqrt() + * ((1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) + * noise_pred + ) + x_next = xt_weighted + weighted_noise_pred + if ( + return_intermediates + and i % (num_steps // return_intermediates) == 0 + and i < num_steps - 1 + ): + intermediates.append(x_next) + inter_steps.append(i) + elif return_intermediates and i >= num_steps - 2: + intermediates.append(x_next) + inter_steps.append(i) + if callback: + callback(i) + + out = {"x_encoded": x_next, "intermediate_steps": inter_steps} + if return_intermediates: + out.update({"intermediates": intermediates}) + return x_next, out + + @torch.no_grad() + def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): + # fast, but does not allow for exact reconstruction + # t serves as an index to gather the correct alphas + if use_original_steps: + sqrt_alphas_cumprod = self.sqrt_alphas_cumprod + sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod + else: + sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) + sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas + + if noise is None: + noise = torch.randn_like(x0) + return ( + extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 + + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise + ) + + @torch.no_grad() + def decode( + self, + x_latent, + cond, + t_start, + unconditional_guidance_scale=1.0, + unconditional_conditioning=None, + use_original_steps=False, + callback=None, + ): + timesteps = ( + np.arange(self.ddpm_num_timesteps) + if use_original_steps + else self.ddim_timesteps + ) + timesteps = timesteps[:t_start] + + time_range = np.flip(timesteps) + total_steps = timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="Decoding image", total=total_steps) + x_dec = x_latent + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full( + (x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long + ) + x_dec, _ = self.p_sample_ddim( + x_dec, + cond, + ts, + index=index, + use_original_steps=use_original_steps, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + ) + if callback: + callback(i) + return x_dec diff --git a/py/iopaint/model/anytext/cldm/embedding_manager.py b/py/iopaint/model/anytext/cldm/embedding_manager.py new file mode 100644 index 0000000..6ccf8a9 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/embedding_manager.py @@ -0,0 +1,165 @@ +''' +Copyright (c) Alibaba, Inc. and its affiliates. +''' +import torch +import torch.nn as nn +import torch.nn.functional as F +from functools import partial +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import conv_nd, linear + + +def get_clip_token_for_string(tokenizer, string): + batch_encoding = tokenizer(string, truncation=True, max_length=77, return_length=True, + return_overflowing_tokens=False, padding="max_length", return_tensors="pt") + tokens = batch_encoding["input_ids"] + assert torch.count_nonzero(tokens - 49407) == 2, f"String '{string}' maps to more than a single token. Please use another string" + return tokens[0, 1] + + +def get_bert_token_for_string(tokenizer, string): + token = tokenizer(string) + assert torch.count_nonzero(token) == 3, f"String '{string}' maps to more than a single token. Please use another string" + token = token[0, 1] + return token + + +def get_clip_vision_emb(encoder, processor, img): + _img = img.repeat(1, 3, 1, 1)*255 + inputs = processor(images=_img, return_tensors="pt") + inputs['pixel_values'] = inputs['pixel_values'].to(img.device) + outputs = encoder(**inputs) + emb = outputs.image_embeds + return emb + + +def get_recog_emb(encoder, img_list): + _img_list = [(img.repeat(1, 3, 1, 1)*255)[0] for img in img_list] + encoder.predictor.eval() + _, preds_neck = encoder.pred_imglist(_img_list, show_debug=False) + return preds_neck + + +def pad_H(x): + _, _, H, W = x.shape + p_top = (W - H) // 2 + p_bot = W - H - p_top + return F.pad(x, (0, 0, p_top, p_bot)) + + +class EncodeNet(nn.Module): + def __init__(self, in_channels, out_channels): + super(EncodeNet, self).__init__() + chan = 16 + n_layer = 4 # downsample + + self.conv1 = conv_nd(2, in_channels, chan, 3, padding=1) + self.conv_list = nn.ModuleList([]) + _c = chan + for i in range(n_layer): + self.conv_list.append(conv_nd(2, _c, _c*2, 3, padding=1, stride=2)) + _c *= 2 + self.conv2 = conv_nd(2, _c, out_channels, 3, padding=1) + self.avgpool = nn.AdaptiveAvgPool2d(1) + self.act = nn.SiLU() + + def forward(self, x): + x = self.act(self.conv1(x)) + for layer in self.conv_list: + x = self.act(layer(x)) + x = self.act(self.conv2(x)) + x = self.avgpool(x) + x = x.view(x.size(0), -1) + return x + + +class EmbeddingManager(nn.Module): + def __init__( + self, + embedder, + valid=True, + glyph_channels=20, + position_channels=1, + placeholder_string='*', + add_pos=False, + emb_type='ocr', + **kwargs + ): + super().__init__() + if hasattr(embedder, 'tokenizer'): # using Stable Diffusion's CLIP encoder + get_token_for_string = partial(get_clip_token_for_string, embedder.tokenizer) + token_dim = 768 + if hasattr(embedder, 'vit'): + assert emb_type == 'vit' + self.get_vision_emb = partial(get_clip_vision_emb, embedder.vit, embedder.processor) + self.get_recog_emb = None + else: # using LDM's BERT encoder + get_token_for_string = partial(get_bert_token_for_string, embedder.tknz_fn) + token_dim = 1280 + self.token_dim = token_dim + self.emb_type = emb_type + + self.add_pos = add_pos + if add_pos: + self.position_encoder = EncodeNet(position_channels, token_dim) + if emb_type == 'ocr': + self.proj = linear(40*64, token_dim) + if emb_type == 'conv': + self.glyph_encoder = EncodeNet(glyph_channels, token_dim) + + self.placeholder_token = get_token_for_string(placeholder_string) + + def encode_text(self, text_info): + if self.get_recog_emb is None and self.emb_type == 'ocr': + self.get_recog_emb = partial(get_recog_emb, self.recog) + + gline_list = [] + pos_list = [] + for i in range(len(text_info['n_lines'])): # sample index in a batch + n_lines = text_info['n_lines'][i] + for j in range(n_lines): # line + gline_list += [text_info['gly_line'][j][i:i+1]] + if self.add_pos: + pos_list += [text_info['positions'][j][i:i+1]] + + if len(gline_list) > 0: + if self.emb_type == 'ocr': + recog_emb = self.get_recog_emb(gline_list) + enc_glyph = self.proj(recog_emb.reshape(recog_emb.shape[0], -1)) + elif self.emb_type == 'vit': + enc_glyph = self.get_vision_emb(pad_H(torch.cat(gline_list, dim=0))) + elif self.emb_type == 'conv': + enc_glyph = self.glyph_encoder(pad_H(torch.cat(gline_list, dim=0))) + if self.add_pos: + enc_pos = self.position_encoder(torch.cat(gline_list, dim=0)) + enc_glyph = enc_glyph+enc_pos + + self.text_embs_all = [] + n_idx = 0 + for i in range(len(text_info['n_lines'])): # sample index in a batch + n_lines = text_info['n_lines'][i] + text_embs = [] + for j in range(n_lines): # line + text_embs += [enc_glyph[n_idx:n_idx+1]] + n_idx += 1 + self.text_embs_all += [text_embs] + + def forward( + self, + tokenized_text, + embedded_text, + ): + b, device = tokenized_text.shape[0], tokenized_text.device + for i in range(b): + idx = tokenized_text[i] == self.placeholder_token.to(device) + if sum(idx) > 0: + if i >= len(self.text_embs_all): + print('truncation for log images...') + break + text_emb = torch.cat(self.text_embs_all[i], dim=0) + if sum(idx) != len(text_emb): + print('truncation for long caption...') + embedded_text[i][idx] = text_emb[:sum(idx)] + return embedded_text + + def embedding_parameters(self): + return self.parameters() diff --git a/py/iopaint/model/anytext/cldm/hack.py b/py/iopaint/model/anytext/cldm/hack.py new file mode 100644 index 0000000..05afe5f --- /dev/null +++ b/py/iopaint/model/anytext/cldm/hack.py @@ -0,0 +1,111 @@ +import torch +import einops + +import iopaint.model.anytext.ldm.modules.encoders.modules +import iopaint.model.anytext.ldm.modules.attention + +from transformers import logging +from iopaint.model.anytext.ldm.modules.attention import default + + +def disable_verbosity(): + logging.set_verbosity_error() + print('logging improved.') + return + + +def enable_sliced_attention(): + iopaint.model.anytext.ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward + print('Enabled sliced_attention.') + return + + +def hack_everything(clip_skip=0): + disable_verbosity() + iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward + iopaint.model.anytext.ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip + print('Enabled clip hacks.') + return + + +# Written by Lvmin +def _hacked_clip_forward(self, text): + PAD = self.tokenizer.pad_token_id + EOS = self.tokenizer.eos_token_id + BOS = self.tokenizer.bos_token_id + + def tokenize(t): + return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"] + + def transformer_encode(t): + if self.clip_skip > 1: + rt = self.transformer(input_ids=t, output_hidden_states=True) + return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip]) + else: + return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state + + def split(x): + return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3] + + def pad(x, p, i): + return x[:i] if len(x) >= i else x + [p] * (i - len(x)) + + raw_tokens_list = tokenize(text) + tokens_list = [] + + for raw_tokens in raw_tokens_list: + raw_tokens_123 = split(raw_tokens) + raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123] + raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123] + tokens_list.append(raw_tokens_123) + + tokens_list = torch.IntTensor(tokens_list).to(self.device) + + feed = einops.rearrange(tokens_list, 'b f i -> (b f) i') + y = transformer_encode(feed) + z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3) + + return z + + +# Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py +def _hacked_sliced_attentin_forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + del context, x + + q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v)) + + limit = k.shape[0] + att_step = 1 + q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0)) + k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0)) + v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0)) + + q_chunks.reverse() + k_chunks.reverse() + v_chunks.reverse() + sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device) + del k, q, v + for i in range(0, limit, att_step): + q_buffer = q_chunks.pop() + k_buffer = k_chunks.pop() + v_buffer = v_chunks.pop() + sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale + + del k_buffer, q_buffer + # attention, what we cannot get enough of, by chunks + + sim_buffer = sim_buffer.softmax(dim=-1) + + sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer) + del v_buffer + sim[i:i + att_step, :, :] = sim_buffer + + del sim_buffer + sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h) + return self.to_out(sim) diff --git a/py/iopaint/model/anytext/cldm/model.py b/py/iopaint/model/anytext/cldm/model.py new file mode 100644 index 0000000..688f2ed --- /dev/null +++ b/py/iopaint/model/anytext/cldm/model.py @@ -0,0 +1,40 @@ +import os +import torch + +from omegaconf import OmegaConf +from iopaint.model.anytext.ldm.util import instantiate_from_config + + +def get_state_dict(d): + return d.get("state_dict", d) + + +def load_state_dict(ckpt_path, location="cpu"): + _, extension = os.path.splitext(ckpt_path) + if extension.lower() == ".safetensors": + import safetensors.torch + + state_dict = safetensors.torch.load_file(ckpt_path, device=location) + else: + state_dict = get_state_dict( + torch.load(ckpt_path, map_location=torch.device(location)) + ) + state_dict = get_state_dict(state_dict) + print(f"Loaded state_dict from [{ckpt_path}]") + return state_dict + + +def create_model(config_path, device, cond_stage_path=None, use_fp16=False): + config = OmegaConf.load(config_path) + # if cond_stage_path: + # config.model.params.cond_stage_config.params.version = ( + # cond_stage_path # use pre-downloaded ckpts, in case blocked + # ) + config.model.params.cond_stage_config.params.device = str(device) + if use_fp16: + config.model.params.use_fp16 = True + config.model.params.control_stage_config.params.use_fp16 = True + config.model.params.unet_config.params.use_fp16 = True + model = instantiate_from_config(config.model).cpu() + print(f"Loaded model config from [{config_path}]") + return model diff --git a/py/iopaint/model/anytext/cldm/recognizer.py b/py/iopaint/model/anytext/cldm/recognizer.py new file mode 100644 index 0000000..0621512 --- /dev/null +++ b/py/iopaint/model/anytext/cldm/recognizer.py @@ -0,0 +1,300 @@ +""" +Copyright (c) Alibaba, Inc. and its affiliates. +""" +import os +import cv2 +import numpy as np +import math +import traceback +from easydict import EasyDict as edict +import time +from iopaint.model.anytext.ocr_recog.RecModel import RecModel +import torch +import torch.nn.functional as F + + +def min_bounding_rect(img): + ret, thresh = cv2.threshold(img, 127, 255, 0) + contours, hierarchy = cv2.findContours( + thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) + if len(contours) == 0: + print("Bad contours, using fake bbox...") + return np.array([[0, 0], [100, 0], [100, 100], [0, 100]]) + max_contour = max(contours, key=cv2.contourArea) + rect = cv2.minAreaRect(max_contour) + box = cv2.boxPoints(rect) + box = np.int0(box) + # sort + x_sorted = sorted(box, key=lambda x: x[0]) + left = x_sorted[:2] + right = x_sorted[2:] + left = sorted(left, key=lambda x: x[1]) + (tl, bl) = left + right = sorted(right, key=lambda x: x[1]) + (tr, br) = right + if tl[1] > bl[1]: + (tl, bl) = (bl, tl) + if tr[1] > br[1]: + (tr, br) = (br, tr) + return np.array([tl, tr, br, bl]) + + +def create_predictor(model_dir=None, model_lang="ch", is_onnx=False): + model_file_path = model_dir + if model_file_path is not None and not os.path.exists(model_file_path): + raise ValueError("not find model file path {}".format(model_file_path)) + + if is_onnx: + import onnxruntime as ort + + sess = ort.InferenceSession( + model_file_path, providers=["CPUExecutionProvider"] + ) # 'TensorrtExecutionProvider', 'CUDAExecutionProvider', 'CPUExecutionProvider' + return sess + else: + if model_lang == "ch": + n_class = 6625 + elif model_lang == "en": + n_class = 97 + else: + raise ValueError(f"Unsupported OCR recog model_lang: {model_lang}") + rec_config = edict( + in_channels=3, + backbone=edict( + type="MobileNetV1Enhance", + scale=0.5, + last_conv_stride=[1, 2], + last_pool_type="avg", + ), + neck=edict( + type="SequenceEncoder", + encoder_type="svtr", + dims=64, + depth=2, + hidden_dims=120, + use_guide=True, + ), + head=edict( + type="CTCHead", + fc_decay=0.00001, + out_channels=n_class, + return_feats=True, + ), + ) + + rec_model = RecModel(rec_config) + if model_file_path is not None: + rec_model.load_state_dict(torch.load(model_file_path, map_location="cpu")) + rec_model.eval() + return rec_model.eval() + + +def _check_image_file(path): + img_end = {"jpg", "bmp", "png", "jpeg", "rgb", "tif", "tiff"} + return any([path.lower().endswith(e) for e in img_end]) + + +def get_image_file_list(img_file): + imgs_lists = [] + if img_file is None or not os.path.exists(img_file): + raise Exception("not found any img file in {}".format(img_file)) + if os.path.isfile(img_file) and _check_image_file(img_file): + imgs_lists.append(img_file) + elif os.path.isdir(img_file): + for single_file in os.listdir(img_file): + file_path = os.path.join(img_file, single_file) + if os.path.isfile(file_path) and _check_image_file(file_path): + imgs_lists.append(file_path) + if len(imgs_lists) == 0: + raise Exception("not found any img file in {}".format(img_file)) + imgs_lists = sorted(imgs_lists) + return imgs_lists + + +class TextRecognizer(object): + def __init__(self, args, predictor): + self.rec_image_shape = [int(v) for v in args.rec_image_shape.split(",")] + self.rec_batch_num = args.rec_batch_num + self.predictor = predictor + self.chars = self.get_char_dict(args.rec_char_dict_path) + self.char2id = {x: i for i, x in enumerate(self.chars)} + self.is_onnx = not isinstance(self.predictor, torch.nn.Module) + self.use_fp16 = args.use_fp16 + + # img: CHW + def resize_norm_img(self, img, max_wh_ratio): + imgC, imgH, imgW = self.rec_image_shape + assert imgC == img.shape[0] + imgW = int((imgH * max_wh_ratio)) + + h, w = img.shape[1:] + ratio = w / float(h) + if math.ceil(imgH * ratio) > imgW: + resized_w = imgW + else: + resized_w = int(math.ceil(imgH * ratio)) + resized_image = torch.nn.functional.interpolate( + img.unsqueeze(0), + size=(imgH, resized_w), + mode="bilinear", + align_corners=True, + ) + resized_image /= 255.0 + resized_image -= 0.5 + resized_image /= 0.5 + padding_im = torch.zeros((imgC, imgH, imgW), dtype=torch.float32).to(img.device) + padding_im[:, :, 0:resized_w] = resized_image[0] + return padding_im + + # img_list: list of tensors with shape chw 0-255 + def pred_imglist(self, img_list, show_debug=False, is_ori=False): + img_num = len(img_list) + assert img_num > 0 + # Calculate the aspect ratio of all text bars + width_list = [] + for img in img_list: + width_list.append(img.shape[2] / float(img.shape[1])) + # Sorting can speed up the recognition process + indices = torch.from_numpy(np.argsort(np.array(width_list))) + batch_num = self.rec_batch_num + preds_all = [None] * img_num + preds_neck_all = [None] * img_num + for beg_img_no in range(0, img_num, batch_num): + end_img_no = min(img_num, beg_img_no + batch_num) + norm_img_batch = [] + + imgC, imgH, imgW = self.rec_image_shape[:3] + max_wh_ratio = imgW / imgH + for ino in range(beg_img_no, end_img_no): + h, w = img_list[indices[ino]].shape[1:] + if h > w * 1.2: + img = img_list[indices[ino]] + img = torch.transpose(img, 1, 2).flip(dims=[1]) + img_list[indices[ino]] = img + h, w = img.shape[1:] + # wh_ratio = w * 1.0 / h + # max_wh_ratio = max(max_wh_ratio, wh_ratio) # comment to not use different ratio + for ino in range(beg_img_no, end_img_no): + norm_img = self.resize_norm_img(img_list[indices[ino]], max_wh_ratio) + if self.use_fp16: + norm_img = norm_img.half() + norm_img = norm_img.unsqueeze(0) + norm_img_batch.append(norm_img) + norm_img_batch = torch.cat(norm_img_batch, dim=0) + if show_debug: + for i in range(len(norm_img_batch)): + _img = norm_img_batch[i].permute(1, 2, 0).detach().cpu().numpy() + _img = (_img + 0.5) * 255 + _img = _img[:, :, ::-1] + file_name = f"{indices[beg_img_no + i]}" + file_name = file_name + "_ori" if is_ori else file_name + cv2.imwrite(file_name + ".jpg", _img) + if self.is_onnx: + input_dict = {} + input_dict[self.predictor.get_inputs()[0].name] = ( + norm_img_batch.detach().cpu().numpy() + ) + outputs = self.predictor.run(None, input_dict) + preds = {} + preds["ctc"] = torch.from_numpy(outputs[0]) + preds["ctc_neck"] = [torch.zeros(1)] * img_num + else: + preds = self.predictor(norm_img_batch) + for rno in range(preds["ctc"].shape[0]): + preds_all[indices[beg_img_no + rno]] = preds["ctc"][rno] + preds_neck_all[indices[beg_img_no + rno]] = preds["ctc_neck"][rno] + + return torch.stack(preds_all, dim=0), torch.stack(preds_neck_all, dim=0) + + def get_char_dict(self, character_dict_path): + character_str = [] + with open(character_dict_path, "rb") as fin: + lines = fin.readlines() + for line in lines: + line = line.decode("utf-8").strip("\n").strip("\r\n") + character_str.append(line) + dict_character = list(character_str) + dict_character = ["sos"] + dict_character + [" "] # eos is space + return dict_character + + def get_text(self, order): + char_list = [self.chars[text_id] for text_id in order] + return "".join(char_list) + + def decode(self, mat): + text_index = mat.detach().cpu().numpy().argmax(axis=1) + ignored_tokens = [0] + selection = np.ones(len(text_index), dtype=bool) + selection[1:] = text_index[1:] != text_index[:-1] + for ignored_token in ignored_tokens: + selection &= text_index != ignored_token + return text_index[selection], np.where(selection)[0] + + def get_ctcloss(self, preds, gt_text, weight): + if not isinstance(weight, torch.Tensor): + weight = torch.tensor(weight).to(preds.device) + ctc_loss = torch.nn.CTCLoss(reduction="none") + log_probs = preds.log_softmax(dim=2).permute(1, 0, 2) # NTC-->TNC + targets = [] + target_lengths = [] + for t in gt_text: + targets += [self.char2id.get(i, len(self.chars) - 1) for i in t] + target_lengths += [len(t)] + targets = torch.tensor(targets).to(preds.device) + target_lengths = torch.tensor(target_lengths).to(preds.device) + input_lengths = torch.tensor([log_probs.shape[0]] * (log_probs.shape[1])).to( + preds.device + ) + loss = ctc_loss(log_probs, targets, input_lengths, target_lengths) + loss = loss / input_lengths * weight + return loss + + +def main(): + rec_model_dir = "./ocr_weights/ppv3_rec.pth" + predictor = create_predictor(rec_model_dir) + args = edict() + args.rec_image_shape = "3, 48, 320" + args.rec_char_dict_path = "./ocr_weights/ppocr_keys_v1.txt" + args.rec_batch_num = 6 + text_recognizer = TextRecognizer(args, predictor) + image_dir = "./test_imgs_cn" + gt_text = ["韩国小馆"] * 14 + + image_file_list = get_image_file_list(image_dir) + valid_image_file_list = [] + img_list = [] + + for image_file in image_file_list: + img = cv2.imread(image_file) + if img is None: + print("error in loading image:{}".format(image_file)) + continue + valid_image_file_list.append(image_file) + img_list.append(torch.from_numpy(img).permute(2, 0, 1).float()) + try: + tic = time.time() + times = [] + for i in range(10): + preds, _ = text_recognizer.pred_imglist(img_list) # get text + preds_all = preds.softmax(dim=2) + times += [(time.time() - tic) * 1000.0] + tic = time.time() + print(times) + print(np.mean(times[1:]) / len(preds_all)) + weight = np.ones(len(gt_text)) + loss = text_recognizer.get_ctcloss(preds, gt_text, weight) + for i in range(len(valid_image_file_list)): + pred = preds_all[i] + order, idx = text_recognizer.decode(pred) + text = text_recognizer.get_text(order) + print( + f'{valid_image_file_list[i]}: pred/gt="{text}"/"{gt_text[i]}", loss={loss[i]:.2f}' + ) + except Exception as E: + print(traceback.format_exc(), E) + + +if __name__ == "__main__": + main() diff --git a/py/iopaint/model/anytext/ldm/__init__.py b/py/iopaint/model/anytext/ldm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/__init__.py b/py/iopaint/model/anytext/ldm/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/autoencoder.py b/py/iopaint/model/anytext/ldm/models/autoencoder.py new file mode 100644 index 0000000..20d52e9 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/autoencoder.py @@ -0,0 +1,218 @@ +import torch +import torch.nn.functional as F +from contextlib import contextmanager + +from iopaint.model.anytext.ldm.modules.diffusionmodules.model import Encoder, Decoder +from iopaint.model.anytext.ldm.modules.distributions.distributions import DiagonalGaussianDistribution + +from iopaint.model.anytext.ldm.util import instantiate_from_config +from iopaint.model.anytext.ldm.modules.ema import LitEma + + +class AutoencoderKL(torch.nn.Module): + def __init__(self, + ddconfig, + lossconfig, + embed_dim, + ckpt_path=None, + ignore_keys=[], + image_key="image", + colorize_nlabels=None, + monitor=None, + ema_decay=None, + learn_logvar=False + ): + super().__init__() + self.learn_logvar = learn_logvar + self.image_key = image_key + self.encoder = Encoder(**ddconfig) + self.decoder = Decoder(**ddconfig) + self.loss = instantiate_from_config(lossconfig) + assert ddconfig["double_z"] + self.quant_conv = torch.nn.Conv2d(2*ddconfig["z_channels"], 2*embed_dim, 1) + self.post_quant_conv = torch.nn.Conv2d(embed_dim, ddconfig["z_channels"], 1) + self.embed_dim = embed_dim + if colorize_nlabels is not None: + assert type(colorize_nlabels)==int + self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1)) + if monitor is not None: + self.monitor = monitor + + self.use_ema = ema_decay is not None + if self.use_ema: + self.ema_decay = ema_decay + assert 0. < ema_decay < 1. + self.model_ema = LitEma(self, decay=ema_decay) + print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") + + if ckpt_path is not None: + self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys) + + def init_from_ckpt(self, path, ignore_keys=list()): + sd = torch.load(path, map_location="cpu")["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + self.load_state_dict(sd, strict=False) + print(f"Restored from {path}") + + @contextmanager + def ema_scope(self, context=None): + if self.use_ema: + self.model_ema.store(self.parameters()) + self.model_ema.copy_to(self) + if context is not None: + print(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.use_ema: + self.model_ema.restore(self.parameters()) + if context is not None: + print(f"{context}: Restored training weights") + + def on_train_batch_end(self, *args, **kwargs): + if self.use_ema: + self.model_ema(self) + + def encode(self, x): + h = self.encoder(x) + moments = self.quant_conv(h) + posterior = DiagonalGaussianDistribution(moments) + return posterior + + def decode(self, z): + z = self.post_quant_conv(z) + dec = self.decoder(z) + return dec + + def forward(self, input, sample_posterior=True): + posterior = self.encode(input) + if sample_posterior: + z = posterior.sample() + else: + z = posterior.mode() + dec = self.decode(z) + return dec, posterior + + def get_input(self, batch, k): + x = batch[k] + if len(x.shape) == 3: + x = x[..., None] + x = x.permute(0, 3, 1, 2).to(memory_format=torch.contiguous_format).float() + return x + + def training_step(self, batch, batch_idx, optimizer_idx): + inputs = self.get_input(batch, self.image_key) + reconstructions, posterior = self(inputs) + + if optimizer_idx == 0: + # train encoder+decoder+logvar + aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step, + last_layer=self.get_last_layer(), split="train") + self.log("aeloss", aeloss, prog_bar=True, logger=True, on_step=True, on_epoch=True) + self.log_dict(log_dict_ae, prog_bar=False, logger=True, on_step=True, on_epoch=False) + return aeloss + + if optimizer_idx == 1: + # train the discriminator + discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, optimizer_idx, self.global_step, + last_layer=self.get_last_layer(), split="train") + + self.log("discloss", discloss, prog_bar=True, logger=True, on_step=True, on_epoch=True) + self.log_dict(log_dict_disc, prog_bar=False, logger=True, on_step=True, on_epoch=False) + return discloss + + def validation_step(self, batch, batch_idx): + log_dict = self._validation_step(batch, batch_idx) + with self.ema_scope(): + log_dict_ema = self._validation_step(batch, batch_idx, postfix="_ema") + return log_dict + + def _validation_step(self, batch, batch_idx, postfix=""): + inputs = self.get_input(batch, self.image_key) + reconstructions, posterior = self(inputs) + aeloss, log_dict_ae = self.loss(inputs, reconstructions, posterior, 0, self.global_step, + last_layer=self.get_last_layer(), split="val"+postfix) + + discloss, log_dict_disc = self.loss(inputs, reconstructions, posterior, 1, self.global_step, + last_layer=self.get_last_layer(), split="val"+postfix) + + self.log(f"val{postfix}/rec_loss", log_dict_ae[f"val{postfix}/rec_loss"]) + self.log_dict(log_dict_ae) + self.log_dict(log_dict_disc) + return self.log_dict + + def configure_optimizers(self): + lr = self.learning_rate + ae_params_list = list(self.encoder.parameters()) + list(self.decoder.parameters()) + list( + self.quant_conv.parameters()) + list(self.post_quant_conv.parameters()) + if self.learn_logvar: + print(f"{self.__class__.__name__}: Learning logvar") + ae_params_list.append(self.loss.logvar) + opt_ae = torch.optim.Adam(ae_params_list, + lr=lr, betas=(0.5, 0.9)) + opt_disc = torch.optim.Adam(self.loss.discriminator.parameters(), + lr=lr, betas=(0.5, 0.9)) + return [opt_ae, opt_disc], [] + + def get_last_layer(self): + return self.decoder.conv_out.weight + + @torch.no_grad() + def log_images(self, batch, only_inputs=False, log_ema=False, **kwargs): + log = dict() + x = self.get_input(batch, self.image_key) + x = x.to(self.device) + if not only_inputs: + xrec, posterior = self(x) + if x.shape[1] > 3: + # colorize with random projection + assert xrec.shape[1] > 3 + x = self.to_rgb(x) + xrec = self.to_rgb(xrec) + log["samples"] = self.decode(torch.randn_like(posterior.sample())) + log["reconstructions"] = xrec + if log_ema or self.use_ema: + with self.ema_scope(): + xrec_ema, posterior_ema = self(x) + if x.shape[1] > 3: + # colorize with random projection + assert xrec_ema.shape[1] > 3 + xrec_ema = self.to_rgb(xrec_ema) + log["samples_ema"] = self.decode(torch.randn_like(posterior_ema.sample())) + log["reconstructions_ema"] = xrec_ema + log["inputs"] = x + return log + + def to_rgb(self, x): + assert self.image_key == "segmentation" + if not hasattr(self, "colorize"): + self.register_buffer("colorize", torch.randn(3, x.shape[1], 1, 1).to(x)) + x = F.conv2d(x, weight=self.colorize) + x = 2.*(x-x.min())/(x.max()-x.min()) - 1. + return x + + +class IdentityFirstStage(torch.nn.Module): + def __init__(self, *args, vq_interface=False, **kwargs): + self.vq_interface = vq_interface + super().__init__() + + def encode(self, x, *args, **kwargs): + return x + + def decode(self, x, *args, **kwargs): + return x + + def quantize(self, x, *args, **kwargs): + if self.vq_interface: + return x, None, [None, None, None] + return x + + def forward(self, x, *args, **kwargs): + return x + diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/__init__.py b/py/iopaint/model/anytext/ldm/models/diffusion/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py b/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py new file mode 100644 index 0000000..f8bbaff --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/ddim.py @@ -0,0 +1,354 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor + + +class DDIMSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta,verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + ucg_schedule=None, + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + ctmp = conditioning[list(conditioning.keys())[0]] + while isinstance(ctmp, list): ctmp = ctmp[0] + cbs = ctmp.shape[0] + # cbs = len(ctmp[0]) + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + + elif isinstance(conditioning, list): + for ctmp in conditioning: + if ctmp.shape[0] != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for DDIM sampling is {size}, eta {eta}') + + samples, intermediates = self.ddim_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ucg_schedule=ucg_schedule + ) + return samples, intermediates + + @torch.no_grad() + def ddim_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None, + ucg_schedule=None): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {'x_inter': [img], 'pred_x0': [img], "index": [10000]} + time_range = reversed(range(0, timesteps)) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + if ucg_schedule is not None: + assert len(ucg_schedule) == len(time_range) + unconditional_guidance_scale = ucg_schedule[i] + + outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold) + img, pred_x0 = outs + if callback: + callback(i) + if img_callback: + img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates['x_inter'].append(img) + intermediates['pred_x0'].append(pred_x0) + intermediates['index'].append(index) + + return img, intermediates + + @torch.no_grad() + def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, + dynamic_threshold=None): + b, *_, device = *x.shape, x.device + + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + model_output = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + if isinstance(c, dict): + assert isinstance(unconditional_conditioning, dict) + c_in = dict() + for k in c: + if isinstance(c[k], list): + c_in[k] = [torch.cat([ + unconditional_conditioning[k][i], + c[k][i]]) for i in range(len(c[k]))] + elif isinstance(c[k], dict): + c_in[k] = dict() + for key in c[k]: + if isinstance(c[k][key], list): + if not isinstance(c[k][key][0], torch.Tensor): + continue + c_in[k][key] = [torch.cat([ + unconditional_conditioning[k][key][i], + c[k][key][i]]) for i in range(len(c[k][key]))] + else: + c_in[k][key] = torch.cat([ + unconditional_conditioning[k][key], + c[k][key]]) + + else: + c_in[k] = torch.cat([ + unconditional_conditioning[k], + c[k]]) + elif isinstance(c, list): + c_in = list() + assert isinstance(unconditional_conditioning, list) + for i in range(len(c)): + c_in.append(torch.cat([unconditional_conditioning[i], c[i]])) + else: + c_in = torch.cat([unconditional_conditioning, c]) + model_uncond, model_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond) + + if self.model.parameterization == "v": + e_t = self.model.predict_eps_from_z_and_v(x, t, model_output) + else: + e_t = model_output + + if score_corrector is not None: + assert self.model.parameterization == "eps", 'not implemented' + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) + + # current prediction for x_0 + if self.model.parameterization != "v": + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + else: + pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output) + + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + + if dynamic_threshold is not None: + raise NotImplementedError() + + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + @torch.no_grad() + def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None, + unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None): + num_reference_steps = self.ddpm_num_timesteps if use_original_steps else self.ddim_timesteps.shape[0] + + assert t_enc <= num_reference_steps + num_steps = t_enc + + if use_original_steps: + alphas_next = self.alphas_cumprod[:num_steps] + alphas = self.alphas_cumprod_prev[:num_steps] + else: + alphas_next = self.ddim_alphas[:num_steps] + alphas = torch.tensor(self.ddim_alphas_prev[:num_steps]) + + x_next = x0 + intermediates = [] + inter_steps = [] + for i in tqdm(range(num_steps), desc='Encoding Image'): + t = torch.full((x0.shape[0],), i, device=self.model.device, dtype=torch.long) + if unconditional_guidance_scale == 1.: + noise_pred = self.model.apply_model(x_next, t, c) + else: + assert unconditional_conditioning is not None + e_t_uncond, noise_pred = torch.chunk( + self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)), + torch.cat((unconditional_conditioning, c))), 2) + noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond) + + xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next + weighted_noise_pred = alphas_next[i].sqrt() * ( + (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred + x_next = xt_weighted + weighted_noise_pred + if return_intermediates and i % ( + num_steps // return_intermediates) == 0 and i < num_steps - 1: + intermediates.append(x_next) + inter_steps.append(i) + elif return_intermediates and i >= num_steps - 2: + intermediates.append(x_next) + inter_steps.append(i) + if callback: callback(i) + + out = {'x_encoded': x_next, 'intermediate_steps': inter_steps} + if return_intermediates: + out.update({'intermediates': intermediates}) + return x_next, out + + @torch.no_grad() + def stochastic_encode(self, x0, t, use_original_steps=False, noise=None): + # fast, but does not allow for exact reconstruction + # t serves as an index to gather the correct alphas + if use_original_steps: + sqrt_alphas_cumprod = self.sqrt_alphas_cumprod + sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod + else: + sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas) + sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas + + if noise is None: + noise = torch.randn_like(x0) + return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 + + extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise) + + @torch.no_grad() + def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None, + use_original_steps=False, callback=None): + + timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps + timesteps = timesteps[:t_start] + + time_range = np.flip(timesteps) + total_steps = timesteps.shape[0] + print(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='Decoding image', total=total_steps) + x_dec = x_latent + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long) + x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning) + if callback: callback(i) + return x_dec \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py b/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py new file mode 100644 index 0000000..9f48918 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/ddpm.py @@ -0,0 +1,2380 @@ +""" +Part of the implementation is borrowed and modified from ControlNet, publicly available at https://github.com/lllyasviel/ControlNet/blob/main/ldm/models/diffusion/ddpm.py +""" + +import torch +import torch.nn as nn +import numpy as np +from torch.optim.lr_scheduler import LambdaLR +from einops import rearrange, repeat +from contextlib import contextmanager, nullcontext +from functools import partial +import itertools +from tqdm import tqdm +from torchvision.utils import make_grid +from omegaconf import ListConfig + +from iopaint.model.anytext.ldm.util import ( + log_txt_as_img, + exists, + default, + ismap, + isimage, + mean_flat, + count_params, + instantiate_from_config, +) +from iopaint.model.anytext.ldm.modules.ema import LitEma +from iopaint.model.anytext.ldm.modules.distributions.distributions import ( + normal_kl, + DiagonalGaussianDistribution, +) +from iopaint.model.anytext.ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + make_beta_schedule, + extract_into_tensor, + noise_like, +) +from iopaint.model.anytext.ldm.models.diffusion.ddim import DDIMSampler +import cv2 + + +__conditioning_keys__ = {"concat": "c_concat", "crossattn": "c_crossattn", "adm": "y"} + +PRINT_DEBUG = False + + +def print_grad(grad): + # print('Gradient:', grad) + # print(grad.shape) + a = grad.max() + b = grad.min() + # print(f'mean={grad.mean():.4f}, max={a:.4f}, min={b:.4f}') + s = 255.0 / (a - b) + c = 255 * (-b / (a - b)) + grad = grad * s + c + # print(f'mean={grad.mean():.4f}, max={grad.max():.4f}, min={grad.min():.4f}') + img = grad[0].permute(1, 2, 0).detach().cpu().numpy() + if img.shape[0] == 512: + cv2.imwrite("grad-img.jpg", img) + elif img.shape[0] == 64: + cv2.imwrite("grad-latent.jpg", img) + + +def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +def uniform_on_device(r1, r2, shape, device): + return (r1 - r2) * torch.rand(*shape, device=device) + r2 + + +class DDPM(torch.nn.Module): + # classic DDPM with Gaussian diffusion, in image space + def __init__( + self, + unet_config, + timesteps=1000, + beta_schedule="linear", + loss_type="l2", + ckpt_path=None, + ignore_keys=[], + load_only_unet=False, + monitor="val/loss", + use_ema=True, + first_stage_key="image", + image_size=256, + channels=3, + log_every_t=100, + clip_denoised=True, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + given_betas=None, + original_elbo_weight=0.0, + v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta + l_simple_weight=1.0, + conditioning_key=None, + parameterization="eps", # all assuming fixed variance schedules + scheduler_config=None, + use_positional_encodings=False, + learn_logvar=False, + logvar_init=0.0, + make_it_fit=False, + ucg_training=None, + reset_ema=False, + reset_num_ema_updates=False, + ): + super().__init__() + assert parameterization in [ + "eps", + "x0", + "v", + ], 'currently only supporting "eps" and "x0" and "v"' + self.parameterization = parameterization + print( + f"{self.__class__.__name__}: Running in {self.parameterization}-prediction mode" + ) + self.cond_stage_model = None + self.clip_denoised = clip_denoised + self.log_every_t = log_every_t + self.first_stage_key = first_stage_key + self.image_size = image_size # try conv? + self.channels = channels + self.use_positional_encodings = use_positional_encodings + self.model = DiffusionWrapper(unet_config, conditioning_key) + count_params(self.model, verbose=True) + self.use_ema = use_ema + if self.use_ema: + self.model_ema = LitEma(self.model) + print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.") + + self.use_scheduler = scheduler_config is not None + if self.use_scheduler: + self.scheduler_config = scheduler_config + + self.v_posterior = v_posterior + self.original_elbo_weight = original_elbo_weight + self.l_simple_weight = l_simple_weight + + if monitor is not None: + self.monitor = monitor + self.make_it_fit = make_it_fit + if reset_ema: + assert exists(ckpt_path) + if ckpt_path is not None: + self.init_from_ckpt( + ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet + ) + if reset_ema: + assert self.use_ema + print( + f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint." + ) + self.model_ema = LitEma(self.model) + if reset_num_ema_updates: + print( + " +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ " + ) + assert self.use_ema + self.model_ema.reset_num_updates() + + self.register_schedule( + given_betas=given_betas, + beta_schedule=beta_schedule, + timesteps=timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + + self.loss_type = loss_type + + self.learn_logvar = learn_logvar + logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,)) + if self.learn_logvar: + self.logvar = nn.Parameter(self.logvar, requires_grad=True) + else: + self.register_buffer("logvar", logvar) + + self.ucg_training = ucg_training or dict() + if self.ucg_training: + self.ucg_prng = np.random.RandomState() + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + if exists(given_betas): + betas = given_betas + else: + betas = make_beta_schedule( + beta_schedule, + timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + alphas = 1.0 - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + # np.save('1.npy', alphas_cumprod) + alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1]) + + (timesteps,) = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert ( + alphas_cumprod.shape[0] == self.num_timesteps + ), "alphas have to be defined for each timestep" + + to_torch = partial(torch.tensor, dtype=torch.float32) + + self.register_buffer("betas", to_torch(betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1)) + ) + + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = (1 - self.v_posterior) * betas * ( + 1.0 - alphas_cumprod_prev + ) / (1.0 - alphas_cumprod) + self.v_posterior * betas + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.register_buffer("posterior_variance", to_torch(posterior_variance)) + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.register_buffer( + "posterior_log_variance_clipped", + to_torch(np.log(np.maximum(posterior_variance, 1e-20))), + ) + self.register_buffer( + "posterior_mean_coef1", + to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)), + ) + self.register_buffer( + "posterior_mean_coef2", + to_torch( + (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod) + ), + ) + + if self.parameterization == "eps": + lvlb_weights = self.betas**2 / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + elif self.parameterization == "x0": + lvlb_weights = ( + 0.5 + * np.sqrt(torch.Tensor(alphas_cumprod)) + / (2.0 * 1 - torch.Tensor(alphas_cumprod)) + ) + elif self.parameterization == "v": + lvlb_weights = torch.ones_like( + self.betas**2 + / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + ) + else: + raise NotImplementedError("mu not supported") + lvlb_weights[0] = lvlb_weights[1] + self.register_buffer("lvlb_weights", lvlb_weights, persistent=False) + assert not torch.isnan(self.lvlb_weights).all() + + @contextmanager + def ema_scope(self, context=None): + if self.use_ema: + self.model_ema.store(self.model.parameters()) + self.model_ema.copy_to(self.model) + if context is not None: + print(f"{context}: Switched to EMA weights") + try: + yield None + finally: + if self.use_ema: + self.model_ema.restore(self.model.parameters()) + if context is not None: + print(f"{context}: Restored training weights") + + @torch.no_grad() + def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): + sd = torch.load(path, map_location="cpu") + if "state_dict" in list(sd.keys()): + sd = sd["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + if self.make_it_fit: + n_params = len( + [ + name + for name, _ in itertools.chain( + self.named_parameters(), self.named_buffers() + ) + ] + ) + for name, param in tqdm( + itertools.chain(self.named_parameters(), self.named_buffers()), + desc="Fitting old weights to new weights", + total=n_params, + ): + if not name in sd: + continue + old_shape = sd[name].shape + new_shape = param.shape + assert len(old_shape) == len(new_shape) + if len(new_shape) > 2: + # we only modify first two axes + assert new_shape[2:] == old_shape[2:] + # assumes first axis corresponds to output dim + if not new_shape == old_shape: + new_param = param.clone() + old_param = sd[name] + if len(new_shape) == 1: + for i in range(new_param.shape[0]): + new_param[i] = old_param[i % old_shape[0]] + elif len(new_shape) >= 2: + for i in range(new_param.shape[0]): + for j in range(new_param.shape[1]): + new_param[i, j] = old_param[ + i % old_shape[0], j % old_shape[1] + ] + + n_used_old = torch.ones(old_shape[1]) + for j in range(new_param.shape[1]): + n_used_old[j % old_shape[1]] += 1 + n_used_new = torch.zeros(new_shape[1]) + for j in range(new_param.shape[1]): + n_used_new[j] = n_used_old[j % old_shape[1]] + + n_used_new = n_used_new[None, :] + while len(n_used_new.shape) < len(new_shape): + n_used_new = n_used_new.unsqueeze(-1) + new_param /= n_used_new + + sd[name] = new_param + + missing, unexpected = ( + self.load_state_dict(sd, strict=False) + if not only_model + else self.model.load_state_dict(sd, strict=False) + ) + print( + f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys" + ) + if len(missing) > 0: + print(f"Missing Keys:\n {missing}") + if len(unexpected) > 0: + print(f"\nUnexpected Keys:\n {unexpected}") + + def q_mean_variance(self, x_start, t): + """ + Get the distribution q(x_t | x_0). + :param x_start: the [N x C x ...] tensor of noiseless inputs. + :param t: the number of diffusion steps (minus 1). Here, 0 means one step. + :return: A tuple (mean, variance, log_variance), all of x_start's shape. + """ + mean = extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) + log_variance = extract_into_tensor( + self.log_one_minus_alphas_cumprod, t, x_start.shape + ) + return mean, variance, log_variance + + def predict_start_from_noise(self, x_t, t, noise): + return ( + extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + * noise + ) + + def predict_start_from_z_and_v(self, x_t, t, v): + # self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) + # self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t + - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v + ) + + def predict_eps_from_z_and_v(self, x_t, t, v): + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) + * x_t + ) + + def q_posterior(self, x_start, x_t, t): + posterior_mean = ( + extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + + extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t + ) + posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape) + posterior_log_variance_clipped = extract_into_tensor( + self.posterior_log_variance_clipped, t, x_t.shape + ) + return posterior_mean, posterior_variance, posterior_log_variance_clipped + + def p_mean_variance(self, x, t, clip_denoised: bool): + model_out = self.model(x, t) + if self.parameterization == "eps": + x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) + elif self.parameterization == "x0": + x_recon = model_out + if clip_denoised: + x_recon.clamp_(-1.0, 1.0) + + model_mean, posterior_variance, posterior_log_variance = self.q_posterior( + x_start=x_recon, x_t=x, t=t + ) + return model_mean, posterior_variance, posterior_log_variance + + @torch.no_grad() + def p_sample(self, x, t, clip_denoised=True, repeat_noise=False): + b, *_, device = *x.shape, x.device + model_mean, _, model_log_variance = self.p_mean_variance( + x=x, t=t, clip_denoised=clip_denoised + ) + noise = noise_like(x.shape, device, repeat_noise) + # no noise when t == 0 + nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) + return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise + + @torch.no_grad() + def p_sample_loop(self, shape, return_intermediates=False): + device = self.betas.device + b = shape[0] + img = torch.randn(shape, device=device) + intermediates = [img] + for i in tqdm( + reversed(range(0, self.num_timesteps)), + desc="Sampling t", + total=self.num_timesteps, + ): + img = self.p_sample( + img, + torch.full((b,), i, device=device, dtype=torch.long), + clip_denoised=self.clip_denoised, + ) + if i % self.log_every_t == 0 or i == self.num_timesteps - 1: + intermediates.append(img) + if return_intermediates: + return img, intermediates + return img + + @torch.no_grad() + def sample(self, batch_size=16, return_intermediates=False): + image_size = self.image_size + channels = self.channels + return self.p_sample_loop( + (batch_size, channels, image_size, image_size), + return_intermediates=return_intermediates, + ) + + def q_sample(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) + * noise + ) + + def get_v(self, x, noise, t): + return ( + extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise + - extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x + ) + + def get_loss(self, pred, target, mean=True): + if self.loss_type == "l1": + loss = (target - pred).abs() + if mean: + loss = loss.mean() + elif self.loss_type == "l2": + if mean: + loss = torch.nn.functional.mse_loss(target, pred) + else: + loss = torch.nn.functional.mse_loss(target, pred, reduction="none") + else: + raise NotImplementedError("unknown loss type '{loss_type}'") + + return loss + + def p_losses(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) + model_out = self.model(x_noisy, t) + + loss_dict = {} + if self.parameterization == "eps": + target = noise + elif self.parameterization == "x0": + target = x_start + elif self.parameterization == "v": + target = self.get_v(x_start, noise, t) + else: + raise NotImplementedError( + f"Parameterization {self.parameterization} not yet supported" + ) + + loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3]) + + log_prefix = "train" if self.training else "val" + + loss_dict.update({f"{log_prefix}/loss_simple": loss.mean()}) + loss_simple = loss.mean() * self.l_simple_weight + + loss_vlb = (self.lvlb_weights[t] * loss).mean() + loss_dict.update({f"{log_prefix}/loss_vlb": loss_vlb}) + + loss = loss_simple + self.original_elbo_weight * loss_vlb + + loss_dict.update({f"{log_prefix}/loss": loss}) + + return loss, loss_dict + + def forward(self, x, *args, **kwargs): + # b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size + # assert h == img_size and w == img_size, f'height and width of image must be {img_size}' + t = torch.randint( + 0, self.num_timesteps, (x.shape[0],), device=self.device + ).long() + return self.p_losses(x, t, *args, **kwargs) + + def get_input(self, batch, k): + x = batch[k] + if len(x.shape) == 3: + x = x[..., None] + x = rearrange(x, "b h w c -> b c h w") + x = x.to(memory_format=torch.contiguous_format).float() + return x + + def shared_step(self, batch): + x = self.get_input(batch, self.first_stage_key) + loss, loss_dict = self(x) + return loss, loss_dict + + def training_step(self, batch, batch_idx): + for k in self.ucg_training: + p = self.ucg_training[k]["p"] + val = self.ucg_training[k]["val"] + if val is None: + val = "" + for i in range(len(batch[k])): + if self.ucg_prng.choice(2, p=[1 - p, p]): + batch[k][i] = val + + loss, loss_dict = self.shared_step(batch) + + self.log_dict( + loss_dict, prog_bar=True, logger=True, on_step=True, on_epoch=True + ) + + self.log( + "global_step", + self.global_step, + prog_bar=True, + logger=True, + on_step=True, + on_epoch=False, + ) + + if self.use_scheduler: + lr = self.optimizers().param_groups[0]["lr"] + self.log( + "lr_abs", lr, prog_bar=True, logger=True, on_step=True, on_epoch=False + ) + + return loss + + @torch.no_grad() + def validation_step(self, batch, batch_idx): + _, loss_dict_no_ema = self.shared_step(batch) + with self.ema_scope(): + _, loss_dict_ema = self.shared_step(batch) + loss_dict_ema = {key + "_ema": loss_dict_ema[key] for key in loss_dict_ema} + self.log_dict( + loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True + ) + self.log_dict( + loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True + ) + + def on_train_batch_end(self, *args, **kwargs): + if self.use_ema: + self.model_ema(self.model) + + def _get_rows_from_list(self, samples): + n_imgs_per_row = len(samples) + denoise_grid = rearrange(samples, "n b c h w -> b n c h w") + denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") + denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) + return denoise_grid + + @torch.no_grad() + def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs): + log = dict() + x = self.get_input(batch, self.first_stage_key) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + x = x.to(self.device)[:N] + log["inputs"] = x + + # get diffusion row + diffusion_row = list() + x_start = x[:n_row] + + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(x_start) + x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise) + diffusion_row.append(x_noisy) + + log["diffusion_row"] = self._get_rows_from_list(diffusion_row) + + if sample: + # get denoise row + with self.ema_scope("Plotting"): + samples, denoise_row = self.sample( + batch_size=N, return_intermediates=True + ) + + log["samples"] = samples + log["denoise_row"] = self._get_rows_from_list(denoise_row) + + if return_keys: + if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: + return log + else: + return {key: log[key] for key in return_keys} + return log + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.model.parameters()) + if self.learn_logvar: + params = params + [self.logvar] + opt = torch.optim.AdamW(params, lr=lr) + return opt + + +class LatentDiffusion(DDPM): + """main class""" + + def __init__( + self, + first_stage_config, + cond_stage_config, + num_timesteps_cond=None, + cond_stage_key="image", + cond_stage_trainable=False, + concat_mode=True, + cond_stage_forward=None, + conditioning_key=None, + scale_factor=1.0, + scale_by_std=False, + force_null_conditioning=False, + *args, + **kwargs, + ): + self.force_null_conditioning = force_null_conditioning + self.num_timesteps_cond = default(num_timesteps_cond, 1) + self.scale_by_std = scale_by_std + assert self.num_timesteps_cond <= kwargs["timesteps"] + # for backwards compatibility after implementation of DiffusionWrapper + if conditioning_key is None: + conditioning_key = "concat" if concat_mode else "crossattn" + if ( + cond_stage_config == "__is_unconditional__" + and not self.force_null_conditioning + ): + conditioning_key = None + ckpt_path = kwargs.pop("ckpt_path", None) + reset_ema = kwargs.pop("reset_ema", False) + reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False) + ignore_keys = kwargs.pop("ignore_keys", []) + super().__init__(conditioning_key=conditioning_key, *args, **kwargs) + self.concat_mode = concat_mode + self.cond_stage_trainable = cond_stage_trainable + self.cond_stage_key = cond_stage_key + try: + self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1 + except: + self.num_downs = 0 + if not scale_by_std: + self.scale_factor = scale_factor + else: + self.register_buffer("scale_factor", torch.tensor(scale_factor)) + self.instantiate_first_stage(first_stage_config) + self.instantiate_cond_stage(cond_stage_config) + self.cond_stage_forward = cond_stage_forward + self.clip_denoised = False + self.bbox_tokenizer = None + + self.restarted_from_ckpt = False + if ckpt_path is not None: + self.init_from_ckpt(ckpt_path, ignore_keys) + self.restarted_from_ckpt = True + if reset_ema: + assert self.use_ema + print( + f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint." + ) + self.model_ema = LitEma(self.model) + if reset_num_ema_updates: + print( + " +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ " + ) + assert self.use_ema + self.model_ema.reset_num_updates() + + def make_cond_schedule( + self, + ): + self.cond_ids = torch.full( + size=(self.num_timesteps,), + fill_value=self.num_timesteps - 1, + dtype=torch.long, + ) + ids = torch.round( + torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond) + ).long() + self.cond_ids[: self.num_timesteps_cond] = ids + + @torch.no_grad() + def on_train_batch_start(self, batch, batch_idx, dataloader_idx): + # only for very first batch + if ( + self.scale_by_std + and self.current_epoch == 0 + and self.global_step == 0 + and batch_idx == 0 + and not self.restarted_from_ckpt + ): + assert ( + self.scale_factor == 1.0 + ), "rather not use custom rescaling and std-rescaling simultaneously" + # set rescale weight to 1./std of encodings + print("### USING STD-RESCALING ###") + x = super().get_input(batch, self.first_stage_key) + x = x.to(self.device) + encoder_posterior = self.encode_first_stage(x) + z = self.get_first_stage_encoding(encoder_posterior).detach() + del self.scale_factor + self.register_buffer("scale_factor", 1.0 / z.flatten().std()) + print(f"setting self.scale_factor to {self.scale_factor}") + print("### USING STD-RESCALING ###") + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + super().register_schedule( + given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s + ) + + self.shorten_cond_schedule = self.num_timesteps_cond > 1 + if self.shorten_cond_schedule: + self.make_cond_schedule() + + def instantiate_first_stage(self, config): + model = instantiate_from_config(config) + self.first_stage_model = model.eval() + self.first_stage_model.train = disabled_train + for param in self.first_stage_model.parameters(): + param.requires_grad = False + + def instantiate_cond_stage(self, config): + if not self.cond_stage_trainable: + if config == "__is_first_stage__": + print("Using first stage also as cond stage.") + self.cond_stage_model = self.first_stage_model + elif config == "__is_unconditional__": + print(f"Training {self.__class__.__name__} as an unconditional model.") + self.cond_stage_model = None + # self.be_unconditional = True + else: + model = instantiate_from_config(config) + self.cond_stage_model = model.eval() + self.cond_stage_model.train = disabled_train + for param in self.cond_stage_model.parameters(): + param.requires_grad = False + else: + assert config != "__is_first_stage__" + assert config != "__is_unconditional__" + model = instantiate_from_config(config) + self.cond_stage_model = model + + def _get_denoise_row_from_list( + self, samples, desc="", force_no_decoder_quantization=False + ): + denoise_row = [] + for zd in tqdm(samples, desc=desc): + denoise_row.append( + self.decode_first_stage( + zd.to(self.device), force_not_quantize=force_no_decoder_quantization + ) + ) + n_imgs_per_row = len(denoise_row) + denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W + denoise_grid = rearrange(denoise_row, "n b c h w -> b n c h w") + denoise_grid = rearrange(denoise_grid, "b n c h w -> (b n) c h w") + denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row) + return denoise_grid + + def get_first_stage_encoding(self, encoder_posterior): + if isinstance(encoder_posterior, DiagonalGaussianDistribution): + z = encoder_posterior.sample() + elif isinstance(encoder_posterior, torch.Tensor): + z = encoder_posterior + else: + raise NotImplementedError( + f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented" + ) + return self.scale_factor * z + + def get_learned_conditioning(self, c): + if self.cond_stage_forward is None: + if hasattr(self.cond_stage_model, "encode") and callable( + self.cond_stage_model.encode + ): + c = self.cond_stage_model.encode(c) + if isinstance(c, DiagonalGaussianDistribution): + c = c.mode() + else: + c = self.cond_stage_model(c) + else: + assert hasattr(self.cond_stage_model, self.cond_stage_forward) + c = getattr(self.cond_stage_model, self.cond_stage_forward)(c) + return c + + def meshgrid(self, h, w): + y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1) + x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1) + + arr = torch.cat([y, x], dim=-1) + return arr + + def delta_border(self, h, w): + """ + :param h: height + :param w: width + :return: normalized distance to image border, + wtith min distance = 0 at border and max dist = 0.5 at image center + """ + lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2) + arr = self.meshgrid(h, w) / lower_right_corner + dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0] + dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0] + edge_dist = torch.min( + torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1 + )[0] + return edge_dist + + def get_weighting(self, h, w, Ly, Lx, device): + weighting = self.delta_border(h, w) + weighting = torch.clip( + weighting, + self.split_input_params["clip_min_weight"], + self.split_input_params["clip_max_weight"], + ) + weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device) + + if self.split_input_params["tie_braker"]: + L_weighting = self.delta_border(Ly, Lx) + L_weighting = torch.clip( + L_weighting, + self.split_input_params["clip_min_tie_weight"], + self.split_input_params["clip_max_tie_weight"], + ) + + L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device) + weighting = weighting * L_weighting + return weighting + + def get_fold_unfold( + self, x, kernel_size, stride, uf=1, df=1 + ): # todo load once not every time, shorten code + """ + :param x: img of size (bs, c, h, w) + :return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1]) + """ + bs, nc, h, w = x.shape + + # number of crops in image + Ly = (h - kernel_size[0]) // stride[0] + 1 + Lx = (w - kernel_size[1]) // stride[1] + 1 + + if uf == 1 and df == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params) + + weighting = self.get_weighting( + kernel_size[0], kernel_size[1], Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap + weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx)) + + elif uf > 1 and df == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold_params2 = dict( + kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf), + dilation=1, + padding=0, + stride=(stride[0] * uf, stride[1] * uf), + ) + fold = torch.nn.Fold( + output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2 + ) + + weighting = self.get_weighting( + kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view( + 1, 1, h * uf, w * uf + ) # normalizes the overlap + weighting = weighting.view( + (1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx) + ) + + elif df > 1 and uf == 1: + fold_params = dict( + kernel_size=kernel_size, dilation=1, padding=0, stride=stride + ) + unfold = torch.nn.Unfold(**fold_params) + + fold_params2 = dict( + kernel_size=(kernel_size[0] // df, kernel_size[0] // df), + dilation=1, + padding=0, + stride=(stride[0] // df, stride[1] // df), + ) + fold = torch.nn.Fold( + output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2 + ) + + weighting = self.get_weighting( + kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device + ).to(x.dtype) + normalization = fold(weighting).view( + 1, 1, h // df, w // df + ) # normalizes the overlap + weighting = weighting.view( + (1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx) + ) + + else: + raise NotImplementedError + + return fold, unfold, normalization, weighting + + @torch.no_grad() + def get_input( + self, + batch, + k, + return_first_stage_outputs=False, + force_c_encode=False, + cond_key=None, + return_original_cond=False, + bs=None, + return_x=False, + mask_k=None, + ): + x = super().get_input(batch, k) + if bs is not None: + x = x[:bs] + x = x.to(self.device) + encoder_posterior = self.encode_first_stage(x) + z = self.get_first_stage_encoding(encoder_posterior).detach() + + if mask_k is not None: + mx = super().get_input(batch, mask_k) + if bs is not None: + mx = mx[:bs] + mx = mx.to(self.device) + encoder_posterior = self.encode_first_stage(mx) + mx = self.get_first_stage_encoding(encoder_posterior).detach() + + if self.model.conditioning_key is not None and not self.force_null_conditioning: + if cond_key is None: + cond_key = self.cond_stage_key + if cond_key != self.first_stage_key: + if cond_key in ["caption", "coordinates_bbox", "txt"]: + xc = batch[cond_key] + elif cond_key in ["class_label", "cls"]: + xc = batch + else: + xc = super().get_input(batch, cond_key).to(self.device) + else: + xc = x + if not self.cond_stage_trainable or force_c_encode: + if isinstance(xc, dict) or isinstance(xc, list): + c = self.get_learned_conditioning(xc) + else: + c = self.get_learned_conditioning(xc.to(self.device)) + else: + c = xc + if bs is not None: + c = c[:bs] + + if self.use_positional_encodings: + pos_x, pos_y = self.compute_latent_shifts(batch) + ckey = __conditioning_keys__[self.model.conditioning_key] + c = {ckey: c, "pos_x": pos_x, "pos_y": pos_y} + + else: + c = None + xc = None + if self.use_positional_encodings: + pos_x, pos_y = self.compute_latent_shifts(batch) + c = {"pos_x": pos_x, "pos_y": pos_y} + out = [z, c] + if return_first_stage_outputs: + xrec = self.decode_first_stage(z) + out.extend([x, xrec]) + if return_x: + out.extend([x]) + if return_original_cond: + out.append(xc) + if mask_k: + out.append(mx) + return out + + @torch.no_grad() + def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False): + if predict_cids: + if z.dim() == 4: + z = torch.argmax(z.exp(), dim=1).long() + z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) + z = rearrange(z, "b h w c -> b c h w").contiguous() + + z = 1.0 / self.scale_factor * z + return self.first_stage_model.decode(z) + + def decode_first_stage_grad(self, z, predict_cids=False, force_not_quantize=False): + if predict_cids: + if z.dim() == 4: + z = torch.argmax(z.exp(), dim=1).long() + z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None) + z = rearrange(z, "b h w c -> b c h w").contiguous() + + z = 1.0 / self.scale_factor * z + return self.first_stage_model.decode(z) + + @torch.no_grad() + def encode_first_stage(self, x): + return self.first_stage_model.encode(x) + + def shared_step(self, batch, **kwargs): + x, c = self.get_input(batch, self.first_stage_key) + loss = self(x, c) + return loss + + def forward(self, x, c, *args, **kwargs): + t = torch.randint( + 0, self.num_timesteps, (x.shape[0],), device=self.device + ).long() + # t = torch.randint(500, 501, (x.shape[0],), device=self.device).long() + if self.model.conditioning_key is not None: + assert c is not None + if self.cond_stage_trainable: + c = self.get_learned_conditioning(c) + if self.shorten_cond_schedule: # TODO: drop this option + tc = self.cond_ids[t].to(self.device) + c = self.q_sample(x_start=c, t=tc, noise=torch.randn_like(c.float())) + return self.p_losses(x, c, t, *args, **kwargs) + + def apply_model(self, x_noisy, t, cond, return_ids=False): + if isinstance(cond, dict): + # hybrid case, cond is expected to be a dict + pass + else: + if not isinstance(cond, list): + cond = [cond] + key = ( + "c_concat" if self.model.conditioning_key == "concat" else "c_crossattn" + ) + cond = {key: cond} + + x_recon = self.model(x_noisy, t, **cond) + + if isinstance(x_recon, tuple) and not return_ids: + return x_recon[0] + else: + return x_recon + + def _predict_eps_from_xstart(self, x_t, t, pred_xstart): + return ( + extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t + - pred_xstart + ) / extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) + + def _prior_bpd(self, x_start): + """ + Get the prior KL term for the variational lower-bound, measured in + bits-per-dim. + This term can't be optimized, as it only depends on the encoder. + :param x_start: the [N x C x ...] tensor of inputs. + :return: a batch of [N] KL values (in bits), one per batch element. + """ + batch_size = x_start.shape[0] + t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) + qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) + kl_prior = normal_kl( + mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 + ) + return mean_flat(kl_prior) / np.log(2.0) + + def p_mean_variance( + self, + x, + c, + t, + clip_denoised: bool, + return_codebook_ids=False, + quantize_denoised=False, + return_x0=False, + score_corrector=None, + corrector_kwargs=None, + ): + t_in = t + model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids) + + if score_corrector is not None: + assert self.parameterization == "eps" + model_out = score_corrector.modify_score( + self, model_out, x, t, c, **corrector_kwargs + ) + + if return_codebook_ids: + model_out, logits = model_out + + if self.parameterization == "eps": + x_recon = self.predict_start_from_noise(x, t=t, noise=model_out) + elif self.parameterization == "x0": + x_recon = model_out + else: + raise NotImplementedError() + + if clip_denoised: + x_recon.clamp_(-1.0, 1.0) + if quantize_denoised: + x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon) + model_mean, posterior_variance, posterior_log_variance = self.q_posterior( + x_start=x_recon, x_t=x, t=t + ) + if return_codebook_ids: + return model_mean, posterior_variance, posterior_log_variance, logits + elif return_x0: + return model_mean, posterior_variance, posterior_log_variance, x_recon + else: + return model_mean, posterior_variance, posterior_log_variance + + @torch.no_grad() + def p_sample( + self, + x, + c, + t, + clip_denoised=False, + repeat_noise=False, + return_codebook_ids=False, + quantize_denoised=False, + return_x0=False, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + ): + b, *_, device = *x.shape, x.device + outputs = self.p_mean_variance( + x=x, + c=c, + t=t, + clip_denoised=clip_denoised, + return_codebook_ids=return_codebook_ids, + quantize_denoised=quantize_denoised, + return_x0=return_x0, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + ) + if return_codebook_ids: + raise DeprecationWarning("Support dropped.") + model_mean, _, model_log_variance, logits = outputs + elif return_x0: + model_mean, _, model_log_variance, x0 = outputs + else: + model_mean, _, model_log_variance = outputs + + noise = noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + # no noise when t == 0 + nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1))) + + if return_codebook_ids: + return model_mean + nonzero_mask * ( + 0.5 * model_log_variance + ).exp() * noise, logits.argmax(dim=1) + if return_x0: + return ( + model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, + x0, + ) + else: + return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise + + @torch.no_grad() + def progressive_denoising( + self, + cond, + shape, + verbose=True, + callback=None, + quantize_denoised=False, + img_callback=None, + mask=None, + x0=None, + temperature=1.0, + noise_dropout=0.0, + score_corrector=None, + corrector_kwargs=None, + batch_size=None, + x_T=None, + start_T=None, + log_every_t=None, + ): + if not log_every_t: + log_every_t = self.log_every_t + timesteps = self.num_timesteps + if batch_size is not None: + b = batch_size if batch_size is not None else shape[0] + shape = [batch_size] + list(shape) + else: + b = batch_size = shape[0] + if x_T is None: + img = torch.randn(shape, device=self.device) + else: + img = x_T + intermediates = [] + if cond is not None: + if isinstance(cond, dict): + cond = { + key: cond[key][:batch_size] + if not isinstance(cond[key], list) + else list(map(lambda x: x[:batch_size], cond[key])) + for key in cond + } + else: + cond = ( + [c[:batch_size] for c in cond] + if isinstance(cond, list) + else cond[:batch_size] + ) + + if start_T is not None: + timesteps = min(timesteps, start_T) + iterator = ( + tqdm( + reversed(range(0, timesteps)), + desc="Progressive Generation", + total=timesteps, + ) + if verbose + else reversed(range(0, timesteps)) + ) + if type(temperature) == float: + temperature = [temperature] * timesteps + + for i in iterator: + ts = torch.full((b,), i, device=self.device, dtype=torch.long) + if self.shorten_cond_schedule: + assert self.model.conditioning_key != "hybrid" + tc = self.cond_ids[ts].to(cond.device) + cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) + + img, x0_partial = self.p_sample( + img, + cond, + ts, + clip_denoised=self.clip_denoised, + quantize_denoised=quantize_denoised, + return_x0=True, + temperature=temperature[i], + noise_dropout=noise_dropout, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + ) + if mask is not None: + assert x0 is not None + img_orig = self.q_sample(x0, ts) + img = img_orig * mask + (1.0 - mask) * img + + if i % log_every_t == 0 or i == timesteps - 1: + intermediates.append(x0_partial) + if callback: + callback(i) + if img_callback: + img_callback(img, i) + return img, intermediates + + @torch.no_grad() + def p_sample_loop( + self, + cond, + shape, + return_intermediates=False, + x_T=None, + verbose=True, + callback=None, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + img_callback=None, + start_T=None, + log_every_t=None, + ): + if not log_every_t: + log_every_t = self.log_every_t + device = self.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + intermediates = [img] + if timesteps is None: + timesteps = self.num_timesteps + + if start_T is not None: + timesteps = min(timesteps, start_T) + iterator = ( + tqdm(reversed(range(0, timesteps)), desc="Sampling t", total=timesteps) + if verbose + else reversed(range(0, timesteps)) + ) + + if mask is not None: + assert x0 is not None + assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match + + for i in iterator: + ts = torch.full((b,), i, device=device, dtype=torch.long) + if self.shorten_cond_schedule: + assert self.model.conditioning_key != "hybrid" + tc = self.cond_ids[ts].to(cond.device) + cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond)) + + img = self.p_sample( + img, + cond, + ts, + clip_denoised=self.clip_denoised, + quantize_denoised=quantize_denoised, + ) + if mask is not None: + img_orig = self.q_sample(x0, ts) + img = img_orig * mask + (1.0 - mask) * img + + if i % log_every_t == 0 or i == timesteps - 1: + intermediates.append(img) + if callback: + callback(i) + if img_callback: + img_callback(img, i) + + if return_intermediates: + return img, intermediates + return img + + @torch.no_grad() + def sample( + self, + cond, + batch_size=16, + return_intermediates=False, + x_T=None, + verbose=True, + timesteps=None, + quantize_denoised=False, + mask=None, + x0=None, + shape=None, + **kwargs, + ): + if shape is None: + shape = (batch_size, self.channels, self.image_size, self.image_size) + if cond is not None: + if isinstance(cond, dict): + cond = { + key: cond[key][:batch_size] + if not isinstance(cond[key], list) + else list(map(lambda x: x[:batch_size], cond[key])) + for key in cond + } + else: + cond = ( + [c[:batch_size] for c in cond] + if isinstance(cond, list) + else cond[:batch_size] + ) + return self.p_sample_loop( + cond, + shape, + return_intermediates=return_intermediates, + x_T=x_T, + verbose=verbose, + timesteps=timesteps, + quantize_denoised=quantize_denoised, + mask=mask, + x0=x0, + ) + + @torch.no_grad() + def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs): + if ddim: + ddim_sampler = DDIMSampler(self) + shape = (self.channels, self.image_size, self.image_size) + samples, intermediates = ddim_sampler.sample( + ddim_steps, batch_size, shape, cond, verbose=False, **kwargs + ) + + else: + samples, intermediates = self.sample( + cond=cond, batch_size=batch_size, return_intermediates=True, **kwargs + ) + + return samples, intermediates + + @torch.no_grad() + def get_unconditional_conditioning(self, batch_size, null_label=None): + if null_label is not None: + xc = null_label + if isinstance(xc, ListConfig): + xc = list(xc) + if isinstance(xc, dict) or isinstance(xc, list): + c = self.get_learned_conditioning(xc) + else: + if hasattr(xc, "to"): + xc = xc.to(self.device) + c = self.get_learned_conditioning(xc) + else: + if self.cond_stage_key in ["class_label", "cls"]: + xc = self.cond_stage_model.get_unconditional_conditioning( + batch_size, device=self.device + ) + return self.get_learned_conditioning(xc) + else: + raise NotImplementedError("todo") + if isinstance(c, list): # in case the encoder gives us a list + for i in range(len(c)): + c[i] = repeat(c[i], "1 ... -> b ...", b=batch_size).to(self.device) + else: + c = repeat(c, "1 ... -> b ...", b=batch_size).to(self.device) + return c + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=50, + ddim_eta=0.0, + return_keys=None, + quantize_denoised=True, + inpaint=True, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc = self.get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=N, + ) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + try: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + except KeyError: + # probably no "human_label" in batch + pass + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if ( + quantize_denoised + and not isinstance(self.first_stage_model, AutoencoderKL) + and not isinstance(self.first_stage_model, IdentityFirstStage) + ): + # also display when quantizing x0 while sampling + with ema_scope("Plotting Quantized Denoised"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + quantize_denoised=True, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True, + # quantize_denoised=True) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_x0_quantized"] = x_samples + + if unconditional_guidance_scale > 1.0: + uc = self.get_unconditional_conditioning(N, unconditional_guidance_label) + if self.model.conditioning_key == "crossattn-adm": + uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]} + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + if inpaint: + # make a simple center square + b, h, w = z.shape[0], z.shape[2], z.shape[3] + mask = torch.ones(N, h, w).to(self.device) + # zeros will be filled in + mask[:, h // 4 : 3 * h // 4, w // 4 : 3 * w // 4] = 0.0 + mask = mask[:, None, ...] + with ema_scope("Plotting Inpaint"): + samples, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + eta=ddim_eta, + ddim_steps=ddim_steps, + x0=z[:N], + mask=mask, + ) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_inpainting"] = x_samples + log["mask"] = mask + + # outpaint + mask = 1.0 - mask + with ema_scope("Plotting Outpaint"): + samples, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + eta=ddim_eta, + ddim_steps=ddim_steps, + x0=z[:N], + mask=mask, + ) + x_samples = self.decode_first_stage(samples.to(self.device)) + log["samples_outpainting"] = x_samples + + if plot_progressive_rows: + with ema_scope("Plotting Progressives"): + img, progressives = self.progressive_denoising( + c, + shape=(self.channels, self.image_size, self.image_size), + batch_size=N, + ) + prog_row = self._get_denoise_row_from_list( + progressives, desc="Progressive Generation" + ) + log["progressive_row"] = prog_row + + if return_keys: + if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0: + return log + else: + return {key: log[key] for key in return_keys} + return log + + def configure_optimizers(self): + lr = self.learning_rate + params = list(self.model.parameters()) + if self.cond_stage_trainable: + print(f"{self.__class__.__name__}: Also optimizing conditioner params!") + params = params + list(self.cond_stage_model.parameters()) + if self.learn_logvar: + print("Diffusion model optimizing logvar") + params.append(self.logvar) + opt = torch.optim.AdamW(params, lr=lr) + if self.use_scheduler: + assert "target" in self.scheduler_config + scheduler = instantiate_from_config(self.scheduler_config) + + print("Setting up LambdaLR scheduler...") + scheduler = [ + { + "scheduler": LambdaLR(opt, lr_lambda=scheduler.schedule), + "interval": "step", + "frequency": 1, + } + ] + return [opt], scheduler + return opt + + @torch.no_grad() + def to_rgb(self, x): + x = x.float() + if not hasattr(self, "colorize"): + self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x) + x = nn.functional.conv2d(x, weight=self.colorize) + x = 2.0 * (x - x.min()) / (x.max() - x.min()) - 1.0 + return x + + +class DiffusionWrapper(torch.nn.Module): + def __init__(self, diff_model_config, conditioning_key): + super().__init__() + self.sequential_cross_attn = diff_model_config.pop( + "sequential_crossattn", False + ) + self.diffusion_model = instantiate_from_config(diff_model_config) + self.conditioning_key = conditioning_key + assert self.conditioning_key in [ + None, + "concat", + "crossattn", + "hybrid", + "adm", + "hybrid-adm", + "crossattn-adm", + ] + + def forward( + self, x, t, c_concat: list = None, c_crossattn: list = None, c_adm=None + ): + if self.conditioning_key is None: + out = self.diffusion_model(x, t) + elif self.conditioning_key == "concat": + xc = torch.cat([x] + c_concat, dim=1) + out = self.diffusion_model(xc, t) + elif self.conditioning_key == "crossattn": + if not self.sequential_cross_attn: + cc = torch.cat(c_crossattn, 1) + else: + cc = c_crossattn + out = self.diffusion_model(x, t, context=cc) + elif self.conditioning_key == "hybrid": + xc = torch.cat([x] + c_concat, dim=1) + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(xc, t, context=cc) + elif self.conditioning_key == "hybrid-adm": + assert c_adm is not None + xc = torch.cat([x] + c_concat, dim=1) + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(xc, t, context=cc, y=c_adm) + elif self.conditioning_key == "crossattn-adm": + assert c_adm is not None + cc = torch.cat(c_crossattn, 1) + out = self.diffusion_model(x, t, context=cc, y=c_adm) + elif self.conditioning_key == "adm": + cc = c_crossattn[0] + out = self.diffusion_model(x, t, y=cc) + else: + raise NotImplementedError() + + return out + + +class LatentUpscaleDiffusion(LatentDiffusion): + def __init__( + self, + *args, + low_scale_config, + low_scale_key="LR", + noise_level_key=None, + **kwargs, + ): + super().__init__(*args, **kwargs) + # assumes that neither the cond_stage nor the low_scale_model contain trainable params + assert not self.cond_stage_trainable + self.instantiate_low_stage(low_scale_config) + self.low_scale_key = low_scale_key + self.noise_level_key = noise_level_key + + def instantiate_low_stage(self, config): + model = instantiate_from_config(config) + self.low_scale_model = model.eval() + self.low_scale_model.train = disabled_train + for param in self.low_scale_model.parameters(): + param.requires_grad = False + + @torch.no_grad() + def get_input(self, batch, k, cond_key=None, bs=None, log_mode=False): + if not log_mode: + z, c = super().get_input(batch, k, force_c_encode=True, bs=bs) + else: + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + x_low = batch[self.low_scale_key][:bs] + x_low = rearrange(x_low, "b h w c -> b c h w") + x_low = x_low.to(memory_format=torch.contiguous_format).float() + zx, noise_level = self.low_scale_model(x_low) + if self.noise_level_key is not None: + # get noise level from batch instead, e.g. when extracting a custom noise level for bsr + raise NotImplementedError("TODO") + + all_conds = {"c_concat": [zx], "c_crossattn": [c], "c_adm": noise_level} + if log_mode: + # TODO: maybe disable if too expensive + x_low_rec = self.low_scale_model.decode(zx) + return z, all_conds, x, xrec, xc, x_low, x_low_rec, noise_level + return z, all_conds + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=200, + ddim_eta=1.0, + return_keys=None, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc, x_low, x_low_rec, noise_level = self.get_input( + batch, self.first_stage_key, bs=N, log_mode=True + ) + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + log["x_lr"] = x_low + log[ + f"x_lr_rec_@noise_levels{'-'.join(map(lambda x: str(x), list(noise_level.cpu().numpy())))}" + ] = x_low_rec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_tmp = self.get_unconditional_conditioning( + N, unconditional_guidance_label + ) + # TODO explore better "unconditional" choices for the other keys + # maybe guide away from empty text label and highest noise level and maximally degraded zx? + uc = dict() + for k in c: + if k == "c_crossattn": + assert isinstance(c[k], list) and len(c[k]) == 1 + uc[k] = [uc_tmp] + elif k == "c_adm": # todo: only run with text-based guidance? + assert isinstance(c[k], torch.Tensor) + # uc[k] = torch.ones_like(c[k]) * self.low_scale_model.max_noise_level + uc[k] = c[k] + elif isinstance(c[k], list): + uc[k] = [c[k][i] for i in range(len(c[k]))] + else: + uc[k] = c[k] + + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond=c, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + if plot_progressive_rows: + with ema_scope("Plotting Progressives"): + img, progressives = self.progressive_denoising( + c, + shape=(self.channels, self.image_size, self.image_size), + batch_size=N, + ) + prog_row = self._get_denoise_row_from_list( + progressives, desc="Progressive Generation" + ) + log["progressive_row"] = prog_row + + return log + + +class LatentFinetuneDiffusion(LatentDiffusion): + """ + Basis for different finetunas, such as inpainting or depth2image + To disable finetuning mode, set finetune_keys to None + """ + + def __init__( + self, + concat_keys: tuple, + finetune_keys=( + "model.diffusion_model.input_blocks.0.0.weight", + "model_ema.diffusion_modelinput_blocks00weight", + ), + keep_finetune_dims=4, + # if model was trained without concat mode before and we would like to keep these channels + c_concat_log_start=None, # to log reconstruction of c_concat codes + c_concat_log_end=None, + *args, + **kwargs, + ): + ckpt_path = kwargs.pop("ckpt_path", None) + ignore_keys = kwargs.pop("ignore_keys", list()) + super().__init__(*args, **kwargs) + self.finetune_keys = finetune_keys + self.concat_keys = concat_keys + self.keep_dims = keep_finetune_dims + self.c_concat_log_start = c_concat_log_start + self.c_concat_log_end = c_concat_log_end + if exists(self.finetune_keys): + assert exists(ckpt_path), "can only finetune from a given checkpoint" + if exists(ckpt_path): + self.init_from_ckpt(ckpt_path, ignore_keys) + + def init_from_ckpt(self, path, ignore_keys=list(), only_model=False): + sd = torch.load(path, map_location="cpu") + if "state_dict" in list(sd.keys()): + sd = sd["state_dict"] + keys = list(sd.keys()) + for k in keys: + for ik in ignore_keys: + if k.startswith(ik): + print("Deleting key {} from state_dict.".format(k)) + del sd[k] + + # make it explicit, finetune by including extra input channels + if exists(self.finetune_keys) and k in self.finetune_keys: + new_entry = None + for name, param in self.named_parameters(): + if name in self.finetune_keys: + print( + f"modifying key '{name}' and keeping its original {self.keep_dims} (channels) dimensions only" + ) + new_entry = torch.zeros_like(param) # zero init + assert exists(new_entry), "did not find matching parameter to modify" + new_entry[:, : self.keep_dims, ...] = sd[k] + sd[k] = new_entry + + missing, unexpected = ( + self.load_state_dict(sd, strict=False) + if not only_model + else self.model.load_state_dict(sd, strict=False) + ) + print( + f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys" + ) + if len(missing) > 0: + print(f"Missing Keys: {missing}") + if len(unexpected) > 0: + print(f"Unexpected Keys: {unexpected}") + + @torch.no_grad() + def log_images( + self, + batch, + N=8, + n_row=4, + sample=True, + ddim_steps=200, + ddim_eta=1.0, + return_keys=None, + quantize_denoised=True, + inpaint=True, + plot_denoise_rows=False, + plot_progressive_rows=True, + plot_diffusion_rows=True, + unconditional_guidance_scale=1.0, + unconditional_guidance_label=None, + use_ema_scope=True, + **kwargs, + ): + ema_scope = self.ema_scope if use_ema_scope else nullcontext + use_ddim = ddim_steps is not None + + log = dict() + z, c, x, xrec, xc = self.get_input( + batch, self.first_stage_key, bs=N, return_first_stage_outputs=True + ) + c_cat, c = c["c_concat"][0], c["c_crossattn"][0] + N = min(x.shape[0], N) + n_row = min(x.shape[0], n_row) + log["inputs"] = x + log["reconstruction"] = xrec + if self.model.conditioning_key is not None: + if hasattr(self.cond_stage_model, "decode"): + xc = self.cond_stage_model.decode(c) + log["conditioning"] = xc + elif self.cond_stage_key in ["caption", "txt"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch[self.cond_stage_key], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif self.cond_stage_key in ["class_label", "cls"]: + xc = log_txt_as_img( + (x.shape[2], x.shape[3]), + batch["human_label"], + size=x.shape[2] // 25, + ) + log["conditioning"] = xc + elif isimage(xc): + log["conditioning"] = xc + if ismap(xc): + log["original_conditioning"] = self.to_rgb(xc) + + if not (self.c_concat_log_start is None and self.c_concat_log_end is None): + log["c_concat_decoded"] = self.decode_first_stage( + c_cat[:, self.c_concat_log_start : self.c_concat_log_end] + ) + + if plot_diffusion_rows: + # get diffusion row + diffusion_row = list() + z_start = z[:n_row] + for t in range(self.num_timesteps): + if t % self.log_every_t == 0 or t == self.num_timesteps - 1: + t = repeat(torch.tensor([t]), "1 -> b", b=n_row) + t = t.to(self.device).long() + noise = torch.randn_like(z_start) + z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise) + diffusion_row.append(self.decode_first_stage(z_noisy)) + + diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W + diffusion_grid = rearrange(diffusion_row, "n b c h w -> b n c h w") + diffusion_grid = rearrange(diffusion_grid, "b n c h w -> (b n) c h w") + diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0]) + log["diffusion_row"] = diffusion_grid + + if sample: + # get denoise row + with ema_scope("Sampling"): + samples, z_denoise_row = self.sample_log( + cond={"c_concat": [c_cat], "c_crossattn": [c]}, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + ) + # samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True) + x_samples = self.decode_first_stage(samples) + log["samples"] = x_samples + if plot_denoise_rows: + denoise_grid = self._get_denoise_row_from_list(z_denoise_row) + log["denoise_row"] = denoise_grid + + if unconditional_guidance_scale > 1.0: + uc_cross = self.get_unconditional_conditioning( + N, unconditional_guidance_label + ) + uc_cat = c_cat + uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]} + with ema_scope("Sampling with classifier-free guidance"): + samples_cfg, _ = self.sample_log( + cond={"c_concat": [c_cat], "c_crossattn": [c]}, + batch_size=N, + ddim=use_ddim, + ddim_steps=ddim_steps, + eta=ddim_eta, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=uc_full, + ) + x_samples_cfg = self.decode_first_stage(samples_cfg) + log[ + f"samples_cfg_scale_{unconditional_guidance_scale:.2f}" + ] = x_samples_cfg + + return log + + +class LatentInpaintDiffusion(LatentFinetuneDiffusion): + """ + can either run as pure inpainting model (only concat mode) or with mixed conditionings, + e.g. mask as concat and text via cross-attn. + To disable finetuning mode, set finetune_keys to None + """ + + def __init__( + self, + concat_keys=("mask", "masked_image"), + masked_image_key="masked_image", + *args, + **kwargs, + ): + super().__init__(concat_keys, *args, **kwargs) + self.masked_image_key = masked_image_key + assert self.masked_image_key in concat_keys + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for inpainting" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + c_cat = list() + for ck in self.concat_keys: + cc = ( + rearrange(batch[ck], "b h w c -> b c h w") + .to(memory_format=torch.contiguous_format) + .float() + ) + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + bchw = z.shape + if ck != self.masked_image_key: + cc = torch.nn.functional.interpolate(cc, size=bchw[-2:]) + else: + cc = self.get_first_stage_encoding(self.encode_first_stage(cc)) + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super(LatentInpaintDiffusion, self).log_images(*args, **kwargs) + log["masked_image"] = ( + rearrange(args[0]["masked_image"], "b h w c -> b c h w") + .to(memory_format=torch.contiguous_format) + .float() + ) + return log + + +class LatentDepth2ImageDiffusion(LatentFinetuneDiffusion): + """ + condition on monocular depth estimation + """ + + def __init__(self, depth_stage_config, concat_keys=("midas_in",), *args, **kwargs): + super().__init__(concat_keys=concat_keys, *args, **kwargs) + self.depth_model = instantiate_from_config(depth_stage_config) + self.depth_stage_key = concat_keys[0] + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for depth2img" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + assert len(self.concat_keys) == 1 + c_cat = list() + for ck in self.concat_keys: + cc = batch[ck] + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + cc = self.depth_model(cc) + cc = torch.nn.functional.interpolate( + cc, + size=z.shape[2:], + mode="bicubic", + align_corners=False, + ) + + depth_min, depth_max = torch.amin( + cc, dim=[1, 2, 3], keepdim=True + ), torch.amax(cc, dim=[1, 2, 3], keepdim=True) + cc = 2.0 * (cc - depth_min) / (depth_max - depth_min + 0.001) - 1.0 + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super().log_images(*args, **kwargs) + depth = self.depth_model(args[0][self.depth_stage_key]) + depth_min, depth_max = torch.amin( + depth, dim=[1, 2, 3], keepdim=True + ), torch.amax(depth, dim=[1, 2, 3], keepdim=True) + log["depth"] = 2.0 * (depth - depth_min) / (depth_max - depth_min) - 1.0 + return log + + +class LatentUpscaleFinetuneDiffusion(LatentFinetuneDiffusion): + """ + condition on low-res image (and optionally on some spatial noise augmentation) + """ + + def __init__( + self, + concat_keys=("lr",), + reshuffle_patch_size=None, + low_scale_config=None, + low_scale_key=None, + *args, + **kwargs, + ): + super().__init__(concat_keys=concat_keys, *args, **kwargs) + self.reshuffle_patch_size = reshuffle_patch_size + self.low_scale_model = None + if low_scale_config is not None: + print("Initializing a low-scale model") + assert exists(low_scale_key) + self.instantiate_low_stage(low_scale_config) + self.low_scale_key = low_scale_key + + def instantiate_low_stage(self, config): + model = instantiate_from_config(config) + self.low_scale_model = model.eval() + self.low_scale_model.train = disabled_train + for param in self.low_scale_model.parameters(): + param.requires_grad = False + + @torch.no_grad() + def get_input( + self, batch, k, cond_key=None, bs=None, return_first_stage_outputs=False + ): + # note: restricted to non-trainable encoders currently + assert ( + not self.cond_stage_trainable + ), "trainable cond stages not yet supported for upscaling-ft" + z, c, x, xrec, xc = super().get_input( + batch, + self.first_stage_key, + return_first_stage_outputs=True, + force_c_encode=True, + return_original_cond=True, + bs=bs, + ) + + assert exists(self.concat_keys) + assert len(self.concat_keys) == 1 + # optionally make spatial noise_level here + c_cat = list() + noise_level = None + for ck in self.concat_keys: + cc = batch[ck] + cc = rearrange(cc, "b h w c -> b c h w") + if exists(self.reshuffle_patch_size): + assert isinstance(self.reshuffle_patch_size, int) + cc = rearrange( + cc, + "b c (p1 h) (p2 w) -> b (p1 p2 c) h w", + p1=self.reshuffle_patch_size, + p2=self.reshuffle_patch_size, + ) + if bs is not None: + cc = cc[:bs] + cc = cc.to(self.device) + if exists(self.low_scale_model) and ck == self.low_scale_key: + cc, noise_level = self.low_scale_model(cc) + c_cat.append(cc) + c_cat = torch.cat(c_cat, dim=1) + if exists(noise_level): + all_conds = {"c_concat": [c_cat], "c_crossattn": [c], "c_adm": noise_level} + else: + all_conds = {"c_concat": [c_cat], "c_crossattn": [c]} + if return_first_stage_outputs: + return z, all_conds, x, xrec, xc + return z, all_conds + + @torch.no_grad() + def log_images(self, *args, **kwargs): + log = super().log_images(*args, **kwargs) + log["lr"] = rearrange(args[0]["lr"], "b h w c -> b c h w") + return log diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py new file mode 100644 index 0000000..7427f38 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/__init__.py @@ -0,0 +1 @@ +from .sampler import DPMSolverSampler \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py new file mode 100644 index 0000000..095e5ba --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/dpm_solver.py @@ -0,0 +1,1154 @@ +import torch +import torch.nn.functional as F +import math +from tqdm import tqdm + + +class NoiseScheduleVP: + def __init__( + self, + schedule='discrete', + betas=None, + alphas_cumprod=None, + continuous_beta_0=0.1, + continuous_beta_1=20., + ): + """Create a wrapper class for the forward SDE (VP type). + *** + Update: We support discrete-time diffusion models by implementing a picewise linear interpolation for log_alpha_t. + We recommend to use schedule='discrete' for the discrete-time diffusion models, especially for high-resolution images. + *** + The forward SDE ensures that the condition distribution q_{t|0}(x_t | x_0) = N ( alpha_t * x_0, sigma_t^2 * I ). + We further define lambda_t = log(alpha_t) - log(sigma_t), which is the half-logSNR (described in the DPM-Solver paper). + Therefore, we implement the functions for computing alpha_t, sigma_t and lambda_t. For t in [0, T], we have: + log_alpha_t = self.marginal_log_mean_coeff(t) + sigma_t = self.marginal_std(t) + lambda_t = self.marginal_lambda(t) + Moreover, as lambda(t) is an invertible function, we also support its inverse function: + t = self.inverse_lambda(lambda_t) + =============================================================== + We support both discrete-time DPMs (trained on n = 0, 1, ..., N-1) and continuous-time DPMs (trained on t in [t_0, T]). + 1. For discrete-time DPMs: + For discrete-time DPMs trained on n = 0, 1, ..., N-1, we convert the discrete steps to continuous time steps by: + t_i = (i + 1) / N + e.g. for N = 1000, we have t_0 = 1e-3 and T = t_{N-1} = 1. + We solve the corresponding diffusion ODE from time T = 1 to time t_0 = 1e-3. + Args: + betas: A `torch.Tensor`. The beta array for the discrete-time DPM. (See the original DDPM paper for details) + alphas_cumprod: A `torch.Tensor`. The cumprod alphas for the discrete-time DPM. (See the original DDPM paper for details) + Note that we always have alphas_cumprod = cumprod(betas). Therefore, we only need to set one of `betas` and `alphas_cumprod`. + **Important**: Please pay special attention for the args for `alphas_cumprod`: + The `alphas_cumprod` is the \hat{alpha_n} arrays in the notations of DDPM. Specifically, DDPMs assume that + q_{t_n | 0}(x_{t_n} | x_0) = N ( \sqrt{\hat{alpha_n}} * x_0, (1 - \hat{alpha_n}) * I ). + Therefore, the notation \hat{alpha_n} is different from the notation alpha_t in DPM-Solver. In fact, we have + alpha_{t_n} = \sqrt{\hat{alpha_n}}, + and + log(alpha_{t_n}) = 0.5 * log(\hat{alpha_n}). + 2. For continuous-time DPMs: + We support two types of VPSDEs: linear (DDPM) and cosine (improved-DDPM). The hyperparameters for the noise + schedule are the default settings in DDPM and improved-DDPM: + Args: + beta_min: A `float` number. The smallest beta for the linear schedule. + beta_max: A `float` number. The largest beta for the linear schedule. + cosine_s: A `float` number. The hyperparameter in the cosine schedule. + cosine_beta_max: A `float` number. The hyperparameter in the cosine schedule. + T: A `float` number. The ending time of the forward process. + =============================================================== + Args: + schedule: A `str`. The noise schedule of the forward SDE. 'discrete' for discrete-time DPMs, + 'linear' or 'cosine' for continuous-time DPMs. + Returns: + A wrapper object of the forward SDE (VP type). + + =============================================================== + Example: + # For discrete-time DPMs, given betas (the beta array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', betas=betas) + # For discrete-time DPMs, given alphas_cumprod (the \hat{alpha_n} array for n = 0, 1, ..., N - 1): + >>> ns = NoiseScheduleVP('discrete', alphas_cumprod=alphas_cumprod) + # For continuous-time DPMs (VPSDE), linear schedule: + >>> ns = NoiseScheduleVP('linear', continuous_beta_0=0.1, continuous_beta_1=20.) + """ + + if schedule not in ['discrete', 'linear', 'cosine']: + raise ValueError( + "Unsupported noise schedule {}. The schedule needs to be 'discrete' or 'linear' or 'cosine'".format( + schedule)) + + self.schedule = schedule + if schedule == 'discrete': + if betas is not None: + log_alphas = 0.5 * torch.log(1 - betas).cumsum(dim=0) + else: + assert alphas_cumprod is not None + log_alphas = 0.5 * torch.log(alphas_cumprod) + self.total_N = len(log_alphas) + self.T = 1. + self.t_array = torch.linspace(0., 1., self.total_N + 1)[1:].reshape((1, -1)) + self.log_alpha_array = log_alphas.reshape((1, -1,)) + else: + self.total_N = 1000 + self.beta_0 = continuous_beta_0 + self.beta_1 = continuous_beta_1 + self.cosine_s = 0.008 + self.cosine_beta_max = 999. + self.cosine_t_max = math.atan(self.cosine_beta_max * (1. + self.cosine_s) / math.pi) * 2. * ( + 1. + self.cosine_s) / math.pi - self.cosine_s + self.cosine_log_alpha_0 = math.log(math.cos(self.cosine_s / (1. + self.cosine_s) * math.pi / 2.)) + self.schedule = schedule + if schedule == 'cosine': + # For the cosine schedule, T = 1 will have numerical issues. So we manually set the ending time T. + # Note that T = 0.9946 may be not the optimal setting. However, we find it works well. + self.T = 0.9946 + else: + self.T = 1. + + def marginal_log_mean_coeff(self, t): + """ + Compute log(alpha_t) of a given continuous-time label t in [0, T]. + """ + if self.schedule == 'discrete': + return interpolate_fn(t.reshape((-1, 1)), self.t_array.to(t.device), + self.log_alpha_array.to(t.device)).reshape((-1)) + elif self.schedule == 'linear': + return -0.25 * t ** 2 * (self.beta_1 - self.beta_0) - 0.5 * t * self.beta_0 + elif self.schedule == 'cosine': + log_alpha_fn = lambda s: torch.log(torch.cos((s + self.cosine_s) / (1. + self.cosine_s) * math.pi / 2.)) + log_alpha_t = log_alpha_fn(t) - self.cosine_log_alpha_0 + return log_alpha_t + + def marginal_alpha(self, t): + """ + Compute alpha_t of a given continuous-time label t in [0, T]. + """ + return torch.exp(self.marginal_log_mean_coeff(t)) + + def marginal_std(self, t): + """ + Compute sigma_t of a given continuous-time label t in [0, T]. + """ + return torch.sqrt(1. - torch.exp(2. * self.marginal_log_mean_coeff(t))) + + def marginal_lambda(self, t): + """ + Compute lambda_t = log(alpha_t) - log(sigma_t) of a given continuous-time label t in [0, T]. + """ + log_mean_coeff = self.marginal_log_mean_coeff(t) + log_std = 0.5 * torch.log(1. - torch.exp(2. * log_mean_coeff)) + return log_mean_coeff - log_std + + def inverse_lambda(self, lamb): + """ + Compute the continuous-time label t in [0, T] of a given half-logSNR lambda_t. + """ + if self.schedule == 'linear': + tmp = 2. * (self.beta_1 - self.beta_0) * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) + Delta = self.beta_0 ** 2 + tmp + return tmp / (torch.sqrt(Delta) + self.beta_0) / (self.beta_1 - self.beta_0) + elif self.schedule == 'discrete': + log_alpha = -0.5 * torch.logaddexp(torch.zeros((1,)).to(lamb.device), -2. * lamb) + t = interpolate_fn(log_alpha.reshape((-1, 1)), torch.flip(self.log_alpha_array.to(lamb.device), [1]), + torch.flip(self.t_array.to(lamb.device), [1])) + return t.reshape((-1,)) + else: + log_alpha = -0.5 * torch.logaddexp(-2. * lamb, torch.zeros((1,)).to(lamb)) + t_fn = lambda log_alpha_t: torch.arccos(torch.exp(log_alpha_t + self.cosine_log_alpha_0)) * 2. * ( + 1. + self.cosine_s) / math.pi - self.cosine_s + t = t_fn(log_alpha) + return t + + +def model_wrapper( + model, + noise_schedule, + model_type="noise", + model_kwargs={}, + guidance_type="uncond", + condition=None, + unconditional_condition=None, + guidance_scale=1., + classifier_fn=None, + classifier_kwargs={}, +): + """Create a wrapper function for the noise prediction model. + DPM-Solver needs to solve the continuous-time diffusion ODEs. For DPMs trained on discrete-time labels, we need to + firstly wrap the model function to a noise prediction model that accepts the continuous time as the input. + We support four types of the diffusion model by setting `model_type`: + 1. "noise": noise prediction model. (Trained by predicting noise). + 2. "x_start": data prediction model. (Trained by predicting the data x_0 at time 0). + 3. "v": velocity prediction model. (Trained by predicting the velocity). + The "v" prediction is derivation detailed in Appendix D of [1], and is used in Imagen-Video [2]. + [1] Salimans, Tim, and Jonathan Ho. "Progressive distillation for fast sampling of diffusion models." + arXiv preprint arXiv:2202.00512 (2022). + [2] Ho, Jonathan, et al. "Imagen Video: High Definition Video Generation with Diffusion Models." + arXiv preprint arXiv:2210.02303 (2022). + + 4. "score": marginal score function. (Trained by denoising score matching). + Note that the score function and the noise prediction model follows a simple relationship: + ``` + noise(x_t, t) = -sigma_t * score(x_t, t) + ``` + We support three types of guided sampling by DPMs by setting `guidance_type`: + 1. "uncond": unconditional sampling by DPMs. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + 2. "classifier": classifier guidance sampling [3] by DPMs and another classifier. + The input `model` has the following format: + `` + model(x, t_input, **model_kwargs) -> noise | x_start | v | score + `` + The input `classifier_fn` has the following format: + `` + classifier_fn(x, t_input, cond, **classifier_kwargs) -> logits(x, t_input, cond) + `` + [3] P. Dhariwal and A. Q. Nichol, "Diffusion models beat GANs on image synthesis," + in Advances in Neural Information Processing Systems, vol. 34, 2021, pp. 8780-8794. + 3. "classifier-free": classifier-free guidance sampling by conditional DPMs. + The input `model` has the following format: + `` + model(x, t_input, cond, **model_kwargs) -> noise | x_start | v | score + `` + And if cond == `unconditional_condition`, the model output is the unconditional DPM output. + [4] Ho, Jonathan, and Tim Salimans. "Classifier-free diffusion guidance." + arXiv preprint arXiv:2207.12598 (2022). + + The `t_input` is the time label of the model, which may be discrete-time labels (i.e. 0 to 999) + or continuous-time labels (i.e. epsilon to T). + We wrap the model function to accept only `x` and `t_continuous` as inputs, and outputs the predicted noise: + `` + def model_fn(x, t_continuous) -> noise: + t_input = get_model_input_time(t_continuous) + return noise_pred(model, x, t_input, **model_kwargs) + `` + where `t_continuous` is the continuous time labels (i.e. epsilon to T). And we use `model_fn` for DPM-Solver. + =============================================================== + Args: + model: A diffusion model with the corresponding format described above. + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + model_type: A `str`. The parameterization type of the diffusion model. + "noise" or "x_start" or "v" or "score". + model_kwargs: A `dict`. A dict for the other inputs of the model function. + guidance_type: A `str`. The type of the guidance for sampling. + "uncond" or "classifier" or "classifier-free". + condition: A pytorch tensor. The condition for the guided sampling. + Only used for "classifier" or "classifier-free" guidance type. + unconditional_condition: A pytorch tensor. The condition for the unconditional sampling. + Only used for "classifier-free" guidance type. + guidance_scale: A `float`. The scale for the guided sampling. + classifier_fn: A classifier function. Only used for the classifier guidance. + classifier_kwargs: A `dict`. A dict for the other inputs of the classifier function. + Returns: + A noise prediction model that accepts the noised data and the continuous time as the inputs. + """ + + def get_model_input_time(t_continuous): + """ + Convert the continuous-time `t_continuous` (in [epsilon, T]) to the model input time. + For discrete-time DPMs, we convert `t_continuous` in [1 / N, 1] to `t_input` in [0, 1000 * (N - 1) / N]. + For continuous-time DPMs, we just use `t_continuous`. + """ + if noise_schedule.schedule == 'discrete': + return (t_continuous - 1. / noise_schedule.total_N) * 1000. + else: + return t_continuous + + def noise_pred_fn(x, t_continuous, cond=None): + if t_continuous.reshape((-1,)).shape[0] == 1: + t_continuous = t_continuous.expand((x.shape[0])) + t_input = get_model_input_time(t_continuous) + if cond is None: + output = model(x, t_input, **model_kwargs) + else: + output = model(x, t_input, cond, **model_kwargs) + if model_type == "noise": + return output + elif model_type == "x_start": + alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return (x - expand_dims(alpha_t, dims) * output) / expand_dims(sigma_t, dims) + elif model_type == "v": + alpha_t, sigma_t = noise_schedule.marginal_alpha(t_continuous), noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return expand_dims(alpha_t, dims) * output + expand_dims(sigma_t, dims) * x + elif model_type == "score": + sigma_t = noise_schedule.marginal_std(t_continuous) + dims = x.dim() + return -expand_dims(sigma_t, dims) * output + + def cond_grad_fn(x, t_input): + """ + Compute the gradient of the classifier, i.e. nabla_{x} log p_t(cond | x_t). + """ + with torch.enable_grad(): + x_in = x.detach().requires_grad_(True) + log_prob = classifier_fn(x_in, t_input, condition, **classifier_kwargs) + return torch.autograd.grad(log_prob.sum(), x_in)[0] + + def model_fn(x, t_continuous): + """ + The noise predicition model function that is used for DPM-Solver. + """ + if t_continuous.reshape((-1,)).shape[0] == 1: + t_continuous = t_continuous.expand((x.shape[0])) + if guidance_type == "uncond": + return noise_pred_fn(x, t_continuous) + elif guidance_type == "classifier": + assert classifier_fn is not None + t_input = get_model_input_time(t_continuous) + cond_grad = cond_grad_fn(x, t_input) + sigma_t = noise_schedule.marginal_std(t_continuous) + noise = noise_pred_fn(x, t_continuous) + return noise - guidance_scale * expand_dims(sigma_t, dims=cond_grad.dim()) * cond_grad + elif guidance_type == "classifier-free": + if guidance_scale == 1. or unconditional_condition is None: + return noise_pred_fn(x, t_continuous, cond=condition) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t_continuous] * 2) + c_in = torch.cat([unconditional_condition, condition]) + noise_uncond, noise = noise_pred_fn(x_in, t_in, cond=c_in).chunk(2) + return noise_uncond + guidance_scale * (noise - noise_uncond) + + assert model_type in ["noise", "x_start", "v"] + assert guidance_type in ["uncond", "classifier", "classifier-free"] + return model_fn + + +class DPM_Solver: + def __init__(self, model_fn, noise_schedule, predict_x0=False, thresholding=False, max_val=1.): + """Construct a DPM-Solver. + We support both the noise prediction model ("predicting epsilon") and the data prediction model ("predicting x0"). + If `predict_x0` is False, we use the solver for the noise prediction model (DPM-Solver). + If `predict_x0` is True, we use the solver for the data prediction model (DPM-Solver++). + In such case, we further support the "dynamic thresholding" in [1] when `thresholding` is True. + The "dynamic thresholding" can greatly improve the sample quality for pixel-space DPMs with large guidance scales. + Args: + model_fn: A noise prediction model function which accepts the continuous-time input (t in [epsilon, T]): + `` + def model_fn(x, t_continuous): + return noise + `` + noise_schedule: A noise schedule object, such as NoiseScheduleVP. + predict_x0: A `bool`. If true, use the data prediction model; else, use the noise prediction model. + thresholding: A `bool`. Valid when `predict_x0` is True. Whether to use the "dynamic thresholding" in [1]. + max_val: A `float`. Valid when both `predict_x0` and `thresholding` are True. The max value for thresholding. + + [1] Chitwan Saharia, William Chan, Saurabh Saxena, Lala Li, Jay Whang, Emily Denton, Seyed Kamyar Seyed Ghasemipour, Burcu Karagol Ayan, S Sara Mahdavi, Rapha Gontijo Lopes, et al. Photorealistic text-to-image diffusion models with deep language understanding. arXiv preprint arXiv:2205.11487, 2022b. + """ + self.model = model_fn + self.noise_schedule = noise_schedule + self.predict_x0 = predict_x0 + self.thresholding = thresholding + self.max_val = max_val + + def noise_prediction_fn(self, x, t): + """ + Return the noise prediction model. + """ + return self.model(x, t) + + def data_prediction_fn(self, x, t): + """ + Return the data prediction model (with thresholding). + """ + noise = self.noise_prediction_fn(x, t) + dims = x.dim() + alpha_t, sigma_t = self.noise_schedule.marginal_alpha(t), self.noise_schedule.marginal_std(t) + x0 = (x - expand_dims(sigma_t, dims) * noise) / expand_dims(alpha_t, dims) + if self.thresholding: + p = 0.995 # A hyperparameter in the paper of "Imagen" [1]. + s = torch.quantile(torch.abs(x0).reshape((x0.shape[0], -1)), p, dim=1) + s = expand_dims(torch.maximum(s, self.max_val * torch.ones_like(s).to(s.device)), dims) + x0 = torch.clamp(x0, -s, s) / s + return x0 + + def model_fn(self, x, t): + """ + Convert the model to the noise prediction model or the data prediction model. + """ + if self.predict_x0: + return self.data_prediction_fn(x, t) + else: + return self.noise_prediction_fn(x, t) + + def get_time_steps(self, skip_type, t_T, t_0, N, device): + """Compute the intermediate time steps for sampling. + Args: + skip_type: A `str`. The type for the spacing of the time steps. We support three types: + - 'logSNR': uniform logSNR for the time steps. + - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.) + - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.) + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + N: A `int`. The total number of the spacing of the time steps. + device: A torch device. + Returns: + A pytorch tensor of the time steps, with the shape (N + 1,). + """ + if skip_type == 'logSNR': + lambda_T = self.noise_schedule.marginal_lambda(torch.tensor(t_T).to(device)) + lambda_0 = self.noise_schedule.marginal_lambda(torch.tensor(t_0).to(device)) + logSNR_steps = torch.linspace(lambda_T.cpu().item(), lambda_0.cpu().item(), N + 1).to(device) + return self.noise_schedule.inverse_lambda(logSNR_steps) + elif skip_type == 'time_uniform': + return torch.linspace(t_T, t_0, N + 1).to(device) + elif skip_type == 'time_quadratic': + t_order = 2 + t = torch.linspace(t_T ** (1. / t_order), t_0 ** (1. / t_order), N + 1).pow(t_order).to(device) + return t + else: + raise ValueError( + "Unsupported skip_type {}, need to be 'logSNR' or 'time_uniform' or 'time_quadratic'".format(skip_type)) + + def get_orders_and_timesteps_for_singlestep_solver(self, steps, order, skip_type, t_T, t_0, device): + """ + Get the order of each step for sampling by the singlestep DPM-Solver. + We combine both DPM-Solver-1,2,3 to use all the function evaluations, which is named as "DPM-Solver-fast". + Given a fixed number of function evaluations by `steps`, the sampling procedure by DPM-Solver-fast is: + - If order == 1: + We take `steps` of DPM-Solver-1 (i.e. DDIM). + - If order == 2: + - Denote K = (steps // 2). We take K or (K + 1) intermediate time steps for sampling. + - If steps % 2 == 0, we use K steps of DPM-Solver-2. + - If steps % 2 == 1, we use K steps of DPM-Solver-2 and 1 step of DPM-Solver-1. + - If order == 3: + - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling. + - If steps % 3 == 0, we use (K - 2) steps of DPM-Solver-3, and 1 step of DPM-Solver-2 and 1 step of DPM-Solver-1. + - If steps % 3 == 1, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-1. + - If steps % 3 == 2, we use (K - 1) steps of DPM-Solver-3 and 1 step of DPM-Solver-2. + ============================================ + Args: + order: A `int`. The max order for the solver (2 or 3). + steps: A `int`. The total number of function evaluations (NFE). + skip_type: A `str`. The type for the spacing of the time steps. We support three types: + - 'logSNR': uniform logSNR for the time steps. + - 'time_uniform': uniform time for the time steps. (**Recommended for high-resolutional data**.) + - 'time_quadratic': quadratic time for the time steps. (Used in DDIM for low-resolutional data.) + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + device: A torch device. + Returns: + orders: A list of the solver order of each step. + """ + if order == 3: + K = steps // 3 + 1 + if steps % 3 == 0: + orders = [3, ] * (K - 2) + [2, 1] + elif steps % 3 == 1: + orders = [3, ] * (K - 1) + [1] + else: + orders = [3, ] * (K - 1) + [2] + elif order == 2: + if steps % 2 == 0: + K = steps // 2 + orders = [2, ] * K + else: + K = steps // 2 + 1 + orders = [2, ] * (K - 1) + [1] + elif order == 1: + K = 1 + orders = [1, ] * steps + else: + raise ValueError("'order' must be '1' or '2' or '3'.") + if skip_type == 'logSNR': + # To reproduce the results in DPM-Solver paper + timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, K, device) + else: + timesteps_outer = self.get_time_steps(skip_type, t_T, t_0, steps, device)[ + torch.cumsum(torch.tensor([0, ] + orders)).to(device)] + return timesteps_outer, orders + + def denoise_to_zero_fn(self, x, s): + """ + Denoise at the final step, which is equivalent to solve the ODE from lambda_s to infty by first-order discretization. + """ + return self.data_prediction_fn(x, s) + + def dpm_solver_first_update(self, x, s, t, model_s=None, return_intermediate=False): + """ + DPM-Solver-1 (equivalent to DDIM) from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s`. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + log_alpha_s, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_t = ns.marginal_std(s), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + if self.predict_x0: + phi_1 = torch.expm1(-h) + if model_s is None: + model_s = self.model_fn(x, s) + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + ) + if return_intermediate: + return x_t, {'model_s': model_s} + else: + return x_t + else: + phi_1 = torch.expm1(h) + if model_s is None: + model_s = self.model_fn(x, s) + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + ) + if return_intermediate: + return x_t, {'model_s': model_s} + else: + return x_t + + def singlestep_dpm_solver_second_update(self, x, s, t, r1=0.5, model_s=None, return_intermediate=False, + solver_type='dpm_solver'): + """ + Singlestep solver DPM-Solver-2 from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + r1: A `float`. The hyperparameter of the second-order solver. + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s` and `s1` (the intermediate time). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + if r1 is None: + r1 = 0.5 + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + lambda_s1 = lambda_s + r1 * h + s1 = ns.inverse_lambda(lambda_s1) + log_alpha_s, log_alpha_s1, log_alpha_t = ns.marginal_log_mean_coeff(s), ns.marginal_log_mean_coeff( + s1), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_s1, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std(t) + alpha_s1, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_t) + + if self.predict_x0: + phi_11 = torch.expm1(-r1 * h) + phi_1 = torch.expm1(-h) + + if model_s is None: + model_s = self.model_fn(x, s) + x_s1 = ( + expand_dims(sigma_s1 / sigma_s, dims) * x + - expand_dims(alpha_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + - (0.5 / r1) * expand_dims(alpha_t * phi_1, dims) * (model_s1 - model_s) + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + (1. / r1) * expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * ( + model_s1 - model_s) + ) + else: + phi_11 = torch.expm1(r1 * h) + phi_1 = torch.expm1(h) + + if model_s is None: + model_s = self.model_fn(x, s) + x_s1 = ( + expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x + - expand_dims(sigma_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (0.5 / r1) * expand_dims(sigma_t * phi_1, dims) * (model_s1 - model_s) + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (1. / r1) * expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * (model_s1 - model_s) + ) + if return_intermediate: + return x_t, {'model_s': model_s, 'model_s1': model_s1} + else: + return x_t + + def singlestep_dpm_solver_third_update(self, x, s, t, r1=1. / 3., r2=2. / 3., model_s=None, model_s1=None, + return_intermediate=False, solver_type='dpm_solver'): + """ + Singlestep solver DPM-Solver-3 from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + r1: A `float`. The hyperparameter of the third-order solver. + r2: A `float`. The hyperparameter of the third-order solver. + model_s: A pytorch tensor. The model function evaluated at time `s`. + If `model_s` is None, we evaluate the model by `x` and `s`; otherwise we directly use it. + model_s1: A pytorch tensor. The model function evaluated at time `s1` (the intermediate time given by `r1`). + If `model_s1` is None, we evaluate the model at `s1`; otherwise we directly use it. + return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + if r1 is None: + r1 = 1. / 3. + if r2 is None: + r2 = 2. / 3. + ns = self.noise_schedule + dims = x.dim() + lambda_s, lambda_t = ns.marginal_lambda(s), ns.marginal_lambda(t) + h = lambda_t - lambda_s + lambda_s1 = lambda_s + r1 * h + lambda_s2 = lambda_s + r2 * h + s1 = ns.inverse_lambda(lambda_s1) + s2 = ns.inverse_lambda(lambda_s2) + log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = ns.marginal_log_mean_coeff( + s), ns.marginal_log_mean_coeff(s1), ns.marginal_log_mean_coeff(s2), ns.marginal_log_mean_coeff(t) + sigma_s, sigma_s1, sigma_s2, sigma_t = ns.marginal_std(s), ns.marginal_std(s1), ns.marginal_std( + s2), ns.marginal_std(t) + alpha_s1, alpha_s2, alpha_t = torch.exp(log_alpha_s1), torch.exp(log_alpha_s2), torch.exp(log_alpha_t) + + if self.predict_x0: + phi_11 = torch.expm1(-r1 * h) + phi_12 = torch.expm1(-r2 * h) + phi_1 = torch.expm1(-h) + phi_22 = torch.expm1(-r2 * h) / (r2 * h) + 1. + phi_2 = phi_1 / h + 1. + phi_3 = phi_2 / h - 0.5 + + if model_s is None: + model_s = self.model_fn(x, s) + if model_s1 is None: + x_s1 = ( + expand_dims(sigma_s1 / sigma_s, dims) * x + - expand_dims(alpha_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + x_s2 = ( + expand_dims(sigma_s2 / sigma_s, dims) * x + - expand_dims(alpha_s2 * phi_12, dims) * model_s + + r2 / r1 * expand_dims(alpha_s2 * phi_22, dims) * (model_s1 - model_s) + ) + model_s2 = self.model_fn(x_s2, s2) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + (1. / r2) * expand_dims(alpha_t * phi_2, dims) * (model_s2 - model_s) + ) + elif solver_type == 'taylor': + D1_0 = (1. / r1) * (model_s1 - model_s) + D1_1 = (1. / r2) * (model_s2 - model_s) + D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1) + D2 = 2. * (D1_1 - D1_0) / (r2 - r1) + x_t = ( + expand_dims(sigma_t / sigma_s, dims) * x + - expand_dims(alpha_t * phi_1, dims) * model_s + + expand_dims(alpha_t * phi_2, dims) * D1 + - expand_dims(alpha_t * phi_3, dims) * D2 + ) + else: + phi_11 = torch.expm1(r1 * h) + phi_12 = torch.expm1(r2 * h) + phi_1 = torch.expm1(h) + phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1. + phi_2 = phi_1 / h - 1. + phi_3 = phi_2 / h - 0.5 + + if model_s is None: + model_s = self.model_fn(x, s) + if model_s1 is None: + x_s1 = ( + expand_dims(torch.exp(log_alpha_s1 - log_alpha_s), dims) * x + - expand_dims(sigma_s1 * phi_11, dims) * model_s + ) + model_s1 = self.model_fn(x_s1, s1) + x_s2 = ( + expand_dims(torch.exp(log_alpha_s2 - log_alpha_s), dims) * x + - expand_dims(sigma_s2 * phi_12, dims) * model_s + - r2 / r1 * expand_dims(sigma_s2 * phi_22, dims) * (model_s1 - model_s) + ) + model_s2 = self.model_fn(x_s2, s2) + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - (1. / r2) * expand_dims(sigma_t * phi_2, dims) * (model_s2 - model_s) + ) + elif solver_type == 'taylor': + D1_0 = (1. / r1) * (model_s1 - model_s) + D1_1 = (1. / r2) * (model_s2 - model_s) + D1 = (r2 * D1_0 - r1 * D1_1) / (r2 - r1) + D2 = 2. * (D1_1 - D1_0) / (r2 - r1) + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_s), dims) * x + - expand_dims(sigma_t * phi_1, dims) * model_s + - expand_dims(sigma_t * phi_2, dims) * D1 + - expand_dims(sigma_t * phi_3, dims) * D2 + ) + + if return_intermediate: + return x_t, {'model_s': model_s, 'model_s1': model_s1, 'model_s2': model_s2} + else: + return x_t + + def multistep_dpm_solver_second_update(self, x, model_prev_list, t_prev_list, t, solver_type="dpm_solver"): + """ + Multistep solver DPM-Solver-2 from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if solver_type not in ['dpm_solver', 'taylor']: + raise ValueError("'solver_type' must be either 'dpm_solver' or 'taylor', got {}".format(solver_type)) + ns = self.noise_schedule + dims = x.dim() + model_prev_1, model_prev_0 = model_prev_list + t_prev_1, t_prev_0 = t_prev_list + lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_1), ns.marginal_lambda( + t_prev_0), ns.marginal_lambda(t) + log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) + sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + h_0 = lambda_prev_0 - lambda_prev_1 + h = lambda_t - lambda_prev_0 + r0 = h_0 / h + D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1) + if self.predict_x0: + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + - 0.5 * expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * D1_0 + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1_0 + ) + else: + if solver_type == 'dpm_solver': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - 0.5 * expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * D1_0 + ) + elif solver_type == 'taylor': + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1_0 + ) + return x_t + + def multistep_dpm_solver_third_update(self, x, model_prev_list, t_prev_list, t, solver_type='dpm_solver'): + """ + Multistep solver DPM-Solver-3 from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + ns = self.noise_schedule + dims = x.dim() + model_prev_2, model_prev_1, model_prev_0 = model_prev_list + t_prev_2, t_prev_1, t_prev_0 = t_prev_list + lambda_prev_2, lambda_prev_1, lambda_prev_0, lambda_t = ns.marginal_lambda(t_prev_2), ns.marginal_lambda( + t_prev_1), ns.marginal_lambda(t_prev_0), ns.marginal_lambda(t) + log_alpha_prev_0, log_alpha_t = ns.marginal_log_mean_coeff(t_prev_0), ns.marginal_log_mean_coeff(t) + sigma_prev_0, sigma_t = ns.marginal_std(t_prev_0), ns.marginal_std(t) + alpha_t = torch.exp(log_alpha_t) + + h_1 = lambda_prev_1 - lambda_prev_2 + h_0 = lambda_prev_0 - lambda_prev_1 + h = lambda_t - lambda_prev_0 + r0, r1 = h_0 / h, h_1 / h + D1_0 = expand_dims(1. / r0, dims) * (model_prev_0 - model_prev_1) + D1_1 = expand_dims(1. / r1, dims) * (model_prev_1 - model_prev_2) + D1 = D1_0 + expand_dims(r0 / (r0 + r1), dims) * (D1_0 - D1_1) + D2 = expand_dims(1. / (r0 + r1), dims) * (D1_0 - D1_1) + if self.predict_x0: + x_t = ( + expand_dims(sigma_t / sigma_prev_0, dims) * x + - expand_dims(alpha_t * (torch.exp(-h) - 1.), dims) * model_prev_0 + + expand_dims(alpha_t * ((torch.exp(-h) - 1.) / h + 1.), dims) * D1 + - expand_dims(alpha_t * ((torch.exp(-h) - 1. + h) / h ** 2 - 0.5), dims) * D2 + ) + else: + x_t = ( + expand_dims(torch.exp(log_alpha_t - log_alpha_prev_0), dims) * x + - expand_dims(sigma_t * (torch.exp(h) - 1.), dims) * model_prev_0 + - expand_dims(sigma_t * ((torch.exp(h) - 1.) / h - 1.), dims) * D1 + - expand_dims(sigma_t * ((torch.exp(h) - 1. - h) / h ** 2 - 0.5), dims) * D2 + ) + return x_t + + def singlestep_dpm_solver_update(self, x, s, t, order, return_intermediate=False, solver_type='dpm_solver', r1=None, + r2=None): + """ + Singlestep DPM-Solver with the order `order` from time `s` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + s: A pytorch tensor. The starting time, with the shape (x.shape[0],). + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3. + return_intermediate: A `bool`. If true, also return the model value at time `s`, `s1` and `s2` (the intermediate times). + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + r1: A `float`. The hyperparameter of the second-order or third-order solver. + r2: A `float`. The hyperparameter of the third-order solver. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if order == 1: + return self.dpm_solver_first_update(x, s, t, return_intermediate=return_intermediate) + elif order == 2: + return self.singlestep_dpm_solver_second_update(x, s, t, return_intermediate=return_intermediate, + solver_type=solver_type, r1=r1) + elif order == 3: + return self.singlestep_dpm_solver_third_update(x, s, t, return_intermediate=return_intermediate, + solver_type=solver_type, r1=r1, r2=r2) + else: + raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order)) + + def multistep_dpm_solver_update(self, x, model_prev_list, t_prev_list, t, order, solver_type='dpm_solver'): + """ + Multistep DPM-Solver with the order `order` from time `t_prev_list[-1]` to time `t`. + Args: + x: A pytorch tensor. The initial value at time `s`. + model_prev_list: A list of pytorch tensor. The previous computed model values. + t_prev_list: A list of pytorch tensor. The previous times, each time has the shape (x.shape[0],) + t: A pytorch tensor. The ending time, with the shape (x.shape[0],). + order: A `int`. The order of DPM-Solver. We only support order == 1 or 2 or 3. + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_t: A pytorch tensor. The approximated solution at time `t`. + """ + if order == 1: + return self.dpm_solver_first_update(x, t_prev_list[-1], t, model_s=model_prev_list[-1]) + elif order == 2: + return self.multistep_dpm_solver_second_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type) + elif order == 3: + return self.multistep_dpm_solver_third_update(x, model_prev_list, t_prev_list, t, solver_type=solver_type) + else: + raise ValueError("Solver order must be 1 or 2 or 3, got {}".format(order)) + + def dpm_solver_adaptive(self, x, order, t_T, t_0, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9, t_err=1e-5, + solver_type='dpm_solver'): + """ + The adaptive step size solver based on singlestep DPM-Solver. + Args: + x: A pytorch tensor. The initial value at time `t_T`. + order: A `int`. The (higher) order of the solver. We only support order == 2 or 3. + t_T: A `float`. The starting time of the sampling (default is T). + t_0: A `float`. The ending time of the sampling (default is epsilon). + h_init: A `float`. The initial step size (for logSNR). + atol: A `float`. The absolute tolerance of the solver. For image data, the default setting is 0.0078, followed [1]. + rtol: A `float`. The relative tolerance of the solver. The default setting is 0.05. + theta: A `float`. The safety hyperparameter for adapting the step size. The default setting is 0.9, followed [1]. + t_err: A `float`. The tolerance for the time. We solve the diffusion ODE until the absolute error between the + current time and `t_0` is less than `t_err`. The default setting is 1e-5. + solver_type: either 'dpm_solver' or 'taylor'. The type for the high-order solvers. + The type slightly impacts the performance. We recommend to use 'dpm_solver' type. + Returns: + x_0: A pytorch tensor. The approximated solution at time `t_0`. + [1] A. Jolicoeur-Martineau, K. Li, R. Piché-Taillefer, T. Kachman, and I. Mitliagkas, "Gotta go fast when generating data with score-based models," arXiv preprint arXiv:2105.14080, 2021. + """ + ns = self.noise_schedule + s = t_T * torch.ones((x.shape[0],)).to(x) + lambda_s = ns.marginal_lambda(s) + lambda_0 = ns.marginal_lambda(t_0 * torch.ones_like(s).to(x)) + h = h_init * torch.ones_like(s).to(x) + x_prev = x + nfe = 0 + if order == 2: + r1 = 0.5 + lower_update = lambda x, s, t: self.dpm_solver_first_update(x, s, t, return_intermediate=True) + higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, + solver_type=solver_type, + **kwargs) + elif order == 3: + r1, r2 = 1. / 3., 2. / 3. + lower_update = lambda x, s, t: self.singlestep_dpm_solver_second_update(x, s, t, r1=r1, + return_intermediate=True, + solver_type=solver_type) + higher_update = lambda x, s, t, **kwargs: self.singlestep_dpm_solver_third_update(x, s, t, r1=r1, r2=r2, + solver_type=solver_type, + **kwargs) + else: + raise ValueError("For adaptive step size solver, order must be 2 or 3, got {}".format(order)) + while torch.abs((s - t_0)).mean() > t_err: + t = ns.inverse_lambda(lambda_s + h) + x_lower, lower_noise_kwargs = lower_update(x, s, t) + x_higher = higher_update(x, s, t, **lower_noise_kwargs) + delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_lower), torch.abs(x_prev))) + norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True)) + E = norm_fn((x_higher - x_lower) / delta).max() + if torch.all(E <= 1.): + x = x_higher + s = t + x_prev = x_lower + lambda_s = ns.marginal_lambda(s) + h = torch.min(theta * h * torch.float_power(E, -1. / order).float(), lambda_0 - lambda_s) + nfe += order + print('adaptive solver nfe', nfe) + return x + + def sample(self, x, steps=20, t_start=None, t_end=None, order=3, skip_type='time_uniform', + method='singlestep', lower_order_final=True, denoise_to_zero=False, solver_type='dpm_solver', + atol=0.0078, rtol=0.05, + ): + """ + Compute the sample at time `t_end` by DPM-Solver, given the initial `x` at time `t_start`. + ===================================================== + We support the following algorithms for both noise prediction model and data prediction model: + - 'singlestep': + Singlestep DPM-Solver (i.e. "DPM-Solver-fast" in the paper), which combines different orders of singlestep DPM-Solver. + We combine all the singlestep solvers with order <= `order` to use up all the function evaluations (steps). + The total number of function evaluations (NFE) == `steps`. + Given a fixed NFE == `steps`, the sampling procedure is: + - If `order` == 1: + - Denote K = steps. We use K steps of DPM-Solver-1 (i.e. DDIM). + - If `order` == 2: + - Denote K = (steps // 2) + (steps % 2). We take K intermediate time steps for sampling. + - If steps % 2 == 0, we use K steps of singlestep DPM-Solver-2. + - If steps % 2 == 1, we use (K - 1) steps of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1. + - If `order` == 3: + - Denote K = (steps // 3 + 1). We take K intermediate time steps for sampling. + - If steps % 3 == 0, we use (K - 2) steps of singlestep DPM-Solver-3, and 1 step of singlestep DPM-Solver-2 and 1 step of DPM-Solver-1. + - If steps % 3 == 1, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of DPM-Solver-1. + - If steps % 3 == 2, we use (K - 1) steps of singlestep DPM-Solver-3 and 1 step of singlestep DPM-Solver-2. + - 'multistep': + Multistep DPM-Solver with the order of `order`. The total number of function evaluations (NFE) == `steps`. + We initialize the first `order` values by lower order multistep solvers. + Given a fixed NFE == `steps`, the sampling procedure is: + Denote K = steps. + - If `order` == 1: + - We use K steps of DPM-Solver-1 (i.e. DDIM). + - If `order` == 2: + - We firstly use 1 step of DPM-Solver-1, then use (K - 1) step of multistep DPM-Solver-2. + - If `order` == 3: + - We firstly use 1 step of DPM-Solver-1, then 1 step of multistep DPM-Solver-2, then (K - 2) step of multistep DPM-Solver-3. + - 'singlestep_fixed': + Fixed order singlestep DPM-Solver (i.e. DPM-Solver-1 or singlestep DPM-Solver-2 or singlestep DPM-Solver-3). + We use singlestep DPM-Solver-`order` for `order`=1 or 2 or 3, with total [`steps` // `order`] * `order` NFE. + - 'adaptive': + Adaptive step size DPM-Solver (i.e. "DPM-Solver-12" and "DPM-Solver-23" in the paper). + We ignore `steps` and use adaptive step size DPM-Solver with a higher order of `order`. + You can adjust the absolute tolerance `atol` and the relative tolerance `rtol` to balance the computatation costs + (NFE) and the sample quality. + - If `order` == 2, we use DPM-Solver-12 which combines DPM-Solver-1 and singlestep DPM-Solver-2. + - If `order` == 3, we use DPM-Solver-23 which combines singlestep DPM-Solver-2 and singlestep DPM-Solver-3. + ===================================================== + Some advices for choosing the algorithm: + - For **unconditional sampling** or **guided sampling with small guidance scale** by DPMs: + Use singlestep DPM-Solver ("DPM-Solver-fast" in the paper) with `order = 3`. + e.g. + >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=False) + >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=3, + skip_type='time_uniform', method='singlestep') + - For **guided sampling with large guidance scale** by DPMs: + Use multistep DPM-Solver with `predict_x0 = True` and `order = 2`. + e.g. + >>> dpm_solver = DPM_Solver(model_fn, noise_schedule, predict_x0=True) + >>> x_sample = dpm_solver.sample(x, steps=steps, t_start=t_start, t_end=t_end, order=2, + skip_type='time_uniform', method='multistep') + We support three types of `skip_type`: + - 'logSNR': uniform logSNR for the time steps. **Recommended for low-resolutional images** + - 'time_uniform': uniform time for the time steps. **Recommended for high-resolutional images**. + - 'time_quadratic': quadratic time for the time steps. + ===================================================== + Args: + x: A pytorch tensor. The initial value at time `t_start` + e.g. if `t_start` == T, then `x` is a sample from the standard normal distribution. + steps: A `int`. The total number of function evaluations (NFE). + t_start: A `float`. The starting time of the sampling. + If `T` is None, we use self.noise_schedule.T (default is 1.0). + t_end: A `float`. The ending time of the sampling. + If `t_end` is None, we use 1. / self.noise_schedule.total_N. + e.g. if total_N == 1000, we have `t_end` == 1e-3. + For discrete-time DPMs: + - We recommend `t_end` == 1. / self.noise_schedule.total_N. + For continuous-time DPMs: + - We recommend `t_end` == 1e-3 when `steps` <= 15; and `t_end` == 1e-4 when `steps` > 15. + order: A `int`. The order of DPM-Solver. + skip_type: A `str`. The type for the spacing of the time steps. 'time_uniform' or 'logSNR' or 'time_quadratic'. + method: A `str`. The method for sampling. 'singlestep' or 'multistep' or 'singlestep_fixed' or 'adaptive'. + denoise_to_zero: A `bool`. Whether to denoise to time 0 at the final step. + Default is `False`. If `denoise_to_zero` is `True`, the total NFE is (`steps` + 1). + This trick is firstly proposed by DDPM (https://arxiv.org/abs/2006.11239) and + score_sde (https://arxiv.org/abs/2011.13456). Such trick can improve the FID + for diffusion models sampling by diffusion SDEs for low-resolutional images + (such as CIFAR-10). However, we observed that such trick does not matter for + high-resolutional images. As it needs an additional NFE, we do not recommend + it for high-resolutional images. + lower_order_final: A `bool`. Whether to use lower order solvers at the final steps. + Only valid for `method=multistep` and `steps < 15`. We empirically find that + this trick is a key to stabilizing the sampling by DPM-Solver with very few steps + (especially for steps <= 10). So we recommend to set it to be `True`. + solver_type: A `str`. The taylor expansion type for the solver. `dpm_solver` or `taylor`. We recommend `dpm_solver`. + atol: A `float`. The absolute tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'. + rtol: A `float`. The relative tolerance of the adaptive step size solver. Valid when `method` == 'adaptive'. + Returns: + x_end: A pytorch tensor. The approximated solution at time `t_end`. + """ + t_0 = 1. / self.noise_schedule.total_N if t_end is None else t_end + t_T = self.noise_schedule.T if t_start is None else t_start + device = x.device + if method == 'adaptive': + with torch.no_grad(): + x = self.dpm_solver_adaptive(x, order=order, t_T=t_T, t_0=t_0, atol=atol, rtol=rtol, + solver_type=solver_type) + elif method == 'multistep': + assert steps >= order + timesteps = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device) + assert timesteps.shape[0] - 1 == steps + with torch.no_grad(): + vec_t = timesteps[0].expand((x.shape[0])) + model_prev_list = [self.model_fn(x, vec_t)] + t_prev_list = [vec_t] + # Init the first `order` values by lower order multistep DPM-Solver. + for init_order in tqdm(range(1, order), desc="DPM init order"): + vec_t = timesteps[init_order].expand(x.shape[0]) + x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, init_order, + solver_type=solver_type) + model_prev_list.append(self.model_fn(x, vec_t)) + t_prev_list.append(vec_t) + # Compute the remaining values by `order`-th order multistep DPM-Solver. + for step in tqdm(range(order, steps + 1), desc="DPM multistep"): + vec_t = timesteps[step].expand(x.shape[0]) + if lower_order_final and steps < 15: + step_order = min(order, steps + 1 - step) + else: + step_order = order + x = self.multistep_dpm_solver_update(x, model_prev_list, t_prev_list, vec_t, step_order, + solver_type=solver_type) + for i in range(order - 1): + t_prev_list[i] = t_prev_list[i + 1] + model_prev_list[i] = model_prev_list[i + 1] + t_prev_list[-1] = vec_t + # We do not need to evaluate the final model value. + if step < steps: + model_prev_list[-1] = self.model_fn(x, vec_t) + elif method in ['singlestep', 'singlestep_fixed']: + if method == 'singlestep': + timesteps_outer, orders = self.get_orders_and_timesteps_for_singlestep_solver(steps=steps, order=order, + skip_type=skip_type, + t_T=t_T, t_0=t_0, + device=device) + elif method == 'singlestep_fixed': + K = steps // order + orders = [order, ] * K + timesteps_outer = self.get_time_steps(skip_type=skip_type, t_T=t_T, t_0=t_0, N=K, device=device) + for i, order in enumerate(orders): + t_T_inner, t_0_inner = timesteps_outer[i], timesteps_outer[i + 1] + timesteps_inner = self.get_time_steps(skip_type=skip_type, t_T=t_T_inner.item(), t_0=t_0_inner.item(), + N=order, device=device) + lambda_inner = self.noise_schedule.marginal_lambda(timesteps_inner) + vec_s, vec_t = t_T_inner.tile(x.shape[0]), t_0_inner.tile(x.shape[0]) + h = lambda_inner[-1] - lambda_inner[0] + r1 = None if order <= 1 else (lambda_inner[1] - lambda_inner[0]) / h + r2 = None if order <= 2 else (lambda_inner[2] - lambda_inner[0]) / h + x = self.singlestep_dpm_solver_update(x, vec_s, vec_t, order, solver_type=solver_type, r1=r1, r2=r2) + if denoise_to_zero: + x = self.denoise_to_zero_fn(x, torch.ones((x.shape[0],)).to(device) * t_0) + return x + + +############################################################# +# other utility functions +############################################################# + +def interpolate_fn(x, xp, yp): + """ + A piecewise linear function y = f(x), using xp and yp as keypoints. + We implement f(x) in a differentiable way (i.e. applicable for autograd). + The function f(x) is well-defined for all x-axis. (For x beyond the bounds of xp, we use the outmost points of xp to define the linear function.) + Args: + x: PyTorch tensor with shape [N, C], where N is the batch size, C is the number of channels (we use C = 1 for DPM-Solver). + xp: PyTorch tensor with shape [C, K], where K is the number of keypoints. + yp: PyTorch tensor with shape [C, K]. + Returns: + The function values f(x), with shape [N, C]. + """ + N, K = x.shape[0], xp.shape[1] + all_x = torch.cat([x.unsqueeze(2), xp.unsqueeze(0).repeat((N, 1, 1))], dim=2) + sorted_all_x, x_indices = torch.sort(all_x, dim=2) + x_idx = torch.argmin(x_indices, dim=2) + cand_start_idx = x_idx - 1 + start_idx = torch.where( + torch.eq(x_idx, 0), + torch.tensor(1, device=x.device), + torch.where( + torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, + ), + ) + end_idx = torch.where(torch.eq(start_idx, cand_start_idx), start_idx + 2, start_idx + 1) + start_x = torch.gather(sorted_all_x, dim=2, index=start_idx.unsqueeze(2)).squeeze(2) + end_x = torch.gather(sorted_all_x, dim=2, index=end_idx.unsqueeze(2)).squeeze(2) + start_idx2 = torch.where( + torch.eq(x_idx, 0), + torch.tensor(0, device=x.device), + torch.where( + torch.eq(x_idx, K), torch.tensor(K - 2, device=x.device), cand_start_idx, + ), + ) + y_positions_expanded = yp.unsqueeze(0).expand(N, -1, -1) + start_y = torch.gather(y_positions_expanded, dim=2, index=start_idx2.unsqueeze(2)).squeeze(2) + end_y = torch.gather(y_positions_expanded, dim=2, index=(start_idx2 + 1).unsqueeze(2)).squeeze(2) + cand = start_y + (x - start_x) * (end_y - start_y) / (end_x - start_x) + return cand + + +def expand_dims(v, dims): + """ + Expand the tensor `v` to the dim `dims`. + Args: + `v`: a PyTorch tensor with shape [N]. + `dim`: a `int`. + Returns: + a PyTorch tensor with shape [N, 1, 1, ..., 1] and the total dimension is `dims`. + """ + return v[(...,) + (None,) * (dims - 1)] \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py new file mode 100644 index 0000000..7d137b8 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/dpm_solver/sampler.py @@ -0,0 +1,87 @@ +"""SAMPLING ONLY.""" +import torch + +from .dpm_solver import NoiseScheduleVP, model_wrapper, DPM_Solver + + +MODEL_TYPES = { + "eps": "noise", + "v": "v" +} + + +class DPMSolverSampler(object): + def __init__(self, model, **kwargs): + super().__init__() + self.model = model + to_torch = lambda x: x.clone().detach().to(torch.float32).to(model.device) + self.register_buffer('alphas_cumprod', to_torch(model.alphas_cumprod)) + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + + print(f'Data shape for DPM-Solver sampling is {size}, sampling steps {S}') + + device = self.model.betas.device + if x_T is None: + img = torch.randn(size, device=device) + else: + img = x_T + + ns = NoiseScheduleVP('discrete', alphas_cumprod=self.alphas_cumprod) + + model_fn = model_wrapper( + lambda x, t, c: self.model.apply_model(x, t, c), + ns, + model_type=MODEL_TYPES[self.model.parameterization], + guidance_type="classifier-free", + condition=conditioning, + unconditional_condition=unconditional_conditioning, + guidance_scale=unconditional_guidance_scale, + ) + + dpm_solver = DPM_Solver(model_fn, ns, predict_x0=True, thresholding=False) + x = dpm_solver.sample(img, steps=S, skip_type="time_uniform", method="multistep", order=2, lower_order_final=True) + + return x.to(device), None \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/plms.py b/py/iopaint/model/anytext/ldm/models/diffusion/plms.py new file mode 100644 index 0000000..5f35d55 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/plms.py @@ -0,0 +1,244 @@ +"""SAMPLING ONLY.""" + +import torch +import numpy as np +from tqdm import tqdm +from functools import partial + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like +from iopaint.model.anytext.ldm.models.diffusion.sampling_util import norm_thresholding + + +class PLMSSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + if type(attr) == torch.Tensor: + if attr.device != torch.device("cuda"): + attr = attr.to(torch.device("cuda")) + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + if ddim_eta != 0: + raise ValueError('ddim_eta must be 0 for PLMS') + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta,verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + S, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=True, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + dynamic_threshold=None, + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for PLMS sampling is {size}') + + samples, intermediates = self.plms_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + dynamic_threshold=dynamic_threshold, + ) + return samples, intermediates + + @torch.no_grad() + def plms_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, + dynamic_threshold=None): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + intermediates = {'x_inter': [img], 'pred_x0': [img]} + time_range = list(reversed(range(0,timesteps))) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running PLMS Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps) + old_eps = [] + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + old_eps=old_eps, t_next=ts_next, + dynamic_threshold=dynamic_threshold) + img, pred_x0, e_t = outs + old_eps.append(e_t) + if len(old_eps) >= 4: + old_eps.pop(0) + if callback: callback(i) + if img_callback: img_callback(pred_x0, i) + + if index % log_every_t == 0 or index == total_steps - 1: + intermediates['x_inter'].append(img) + intermediates['pred_x0'].append(pred_x0) + + return img, intermediates + + @torch.no_grad() + def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None, + dynamic_threshold=None): + b, *_, device = *x.shape, x.device + + def get_model_output(x, t): + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + e_t = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + c_in = torch.cat([unconditional_conditioning, c]) + e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond) + + if score_corrector is not None: + assert self.model.parameterization == "eps" + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + return e_t + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + + def get_x_prev_and_pred_x0(e_t, index): + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + if dynamic_threshold is not None: + pred_x0 = norm_thresholding(pred_x0, dynamic_threshold) + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + e_t = get_model_output(x, t) + if len(old_eps) == 0: + # Pseudo Improved Euler (2nd order) + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index) + e_t_next = get_model_output(x_prev, t_next) + e_t_prime = (e_t + e_t_next) / 2 + elif len(old_eps) == 1: + # 2nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (3 * e_t - old_eps[-1]) / 2 + elif len(old_eps) == 2: + # 3nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12 + elif len(old_eps) >= 3: + # 4nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24 + + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index) + + return x_prev, pred_x0, e_t diff --git a/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py b/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py new file mode 100644 index 0000000..7eff02b --- /dev/null +++ b/py/iopaint/model/anytext/ldm/models/diffusion/sampling_util.py @@ -0,0 +1,22 @@ +import torch +import numpy as np + + +def append_dims(x, target_dims): + """Appends dimensions to the end of a tensor until it has target_dims dimensions. + From https://github.com/crowsonkb/k-diffusion/blob/master/k_diffusion/utils.py""" + dims_to_append = target_dims - x.ndim + if dims_to_append < 0: + raise ValueError(f'input has {x.ndim} dims but target_dims is {target_dims}, which is less') + return x[(...,) + (None,) * dims_to_append] + + +def norm_thresholding(x0, value): + s = append_dims(x0.pow(2).flatten(1).mean(1).sqrt().clamp(min=value), x0.ndim) + return x0 * (value / s) + + +def spatial_norm_thresholding(x0, value): + # b c h w + s = x0.pow(2).mean(1, keepdim=True).sqrt().clamp(min=value) + return x0 * (value / s) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/modules/__init__.py b/py/iopaint/model/anytext/ldm/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/attention.py b/py/iopaint/model/anytext/ldm/modules/attention.py new file mode 100644 index 0000000..df92aa7 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/attention.py @@ -0,0 +1,360 @@ +from inspect import isfunction +import math +import torch +import torch.nn.functional as F +from torch import nn, einsum +from einops import rearrange, repeat +from typing import Optional, Any + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import checkpoint + + +# CrossAttn precision handling +import os + +_ATTN_PRECISION = os.environ.get("ATTN_PRECISION", "fp32") + + +def exists(val): + return val is not None + + +def uniq(arr): + return {el: True for el in arr}.keys() + + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + + +def max_neg_value(t): + return -torch.finfo(t.dtype).max + + +def init_(tensor): + dim = tensor.shape[-1] + std = 1 / math.sqrt(dim) + tensor.uniform_(-std, std) + return tensor + + +# feedforward +class GEGLU(nn.Module): + def __init__(self, dim_in, dim_out): + super().__init__() + self.proj = nn.Linear(dim_in, dim_out * 2) + + def forward(self, x): + x, gate = self.proj(x).chunk(2, dim=-1) + return x * F.gelu(gate) + + +class FeedForward(nn.Module): + def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): + super().__init__() + inner_dim = int(dim * mult) + dim_out = default(dim_out, dim) + project_in = ( + nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) + if not glu + else GEGLU(dim, inner_dim) + ) + + self.net = nn.Sequential( + project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out) + ) + + def forward(self, x): + return self.net(x) + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def Normalize(in_channels): + return torch.nn.GroupNorm( + num_groups=32, num_channels=in_channels, eps=1e-6, affine=True + ) + + +class SpatialSelfAttention(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + q = rearrange(q, "b c h w -> b (h w) c") + k = rearrange(k, "b c h w -> b c (h w)") + w_ = torch.einsum("bij,bjk->bik", q, k) + + w_ = w_ * (int(c) ** (-0.5)) + w_ = torch.nn.functional.softmax(w_, dim=2) + + # attend to values + v = rearrange(v, "b c h w -> b c (h w)") + w_ = rearrange(w_, "b i j -> b j i") + h_ = torch.einsum("bij,bjk->bik", v, w_) + h_ = rearrange(h_, "b c (h w) -> b c h w", h=h) + h_ = self.proj_out(h_) + + return x + h_ + + +class CrossAttention(nn.Module): + def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): + super().__init__() + inner_dim = dim_head * heads + context_dim = default(context_dim, query_dim) + + self.scale = dim_head**-0.5 + self.heads = heads + + self.to_q = nn.Linear(query_dim, inner_dim, bias=False) + self.to_k = nn.Linear(context_dim, inner_dim, bias=False) + self.to_v = nn.Linear(context_dim, inner_dim, bias=False) + + self.to_out = nn.Sequential( + nn.Linear(inner_dim, query_dim), nn.Dropout(dropout) + ) + + def forward(self, x, context=None, mask=None): + h = self.heads + + q = self.to_q(x) + context = default(context, x) + k = self.to_k(context) + v = self.to_v(context) + + q, k, v = map(lambda t: rearrange(t, "b n (h d) -> (b h) n d", h=h), (q, k, v)) + + # force cast to fp32 to avoid overflowing + if _ATTN_PRECISION == "fp32": + with torch.autocast(enabled=False, device_type="cuda"): + q, k = q.float(), k.float() + sim = einsum("b i d, b j d -> b i j", q, k) * self.scale + else: + sim = einsum("b i d, b j d -> b i j", q, k) * self.scale + + del q, k + + if exists(mask): + mask = rearrange(mask, "b ... -> b (...)") + max_neg_value = -torch.finfo(sim.dtype).max + mask = repeat(mask, "b j -> (b h) () j", h=h) + sim.masked_fill_(~mask, max_neg_value) + + # attention, what we cannot get enough of + sim = sim.softmax(dim=-1) + + out = einsum("b i j, b j d -> b i d", sim, v) + out = rearrange(out, "(b h) n d -> b n (h d)", h=h) + return self.to_out(out) + + +class SDPACrossAttention(CrossAttention): + def forward(self, x, context=None, mask=None): + batch_size, sequence_length, inner_dim = x.shape + + if mask is not None: + mask = self.prepare_attention_mask(mask, sequence_length, batch_size) + mask = mask.view(batch_size, self.heads, -1, mask.shape[-1]) + + h = self.heads + q_in = self.to_q(x) + context = default(context, x) + + k_in = self.to_k(context) + v_in = self.to_v(context) + + head_dim = inner_dim // h + q = q_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + k = k_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + v = v_in.view(batch_size, -1, h, head_dim).transpose(1, 2) + + del q_in, k_in, v_in + + dtype = q.dtype + if _ATTN_PRECISION == "fp32": + q, k, v = q.float(), k.float(), v.float() + + # the output of sdp = (batch, num_heads, seq_len, head_dim) + hidden_states = torch.nn.functional.scaled_dot_product_attention( + q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False + ) + + hidden_states = hidden_states.transpose(1, 2).reshape( + batch_size, -1, h * head_dim + ) + hidden_states = hidden_states.to(dtype) + + # linear proj + hidden_states = self.to_out[0](hidden_states) + # dropout + hidden_states = self.to_out[1](hidden_states) + return hidden_states + + +class BasicTransformerBlock(nn.Module): + def __init__( + self, + dim, + n_heads, + d_head, + dropout=0.0, + context_dim=None, + gated_ff=True, + checkpoint=True, + disable_self_attn=False, + ): + super().__init__() + + if hasattr(torch.nn.functional, "scaled_dot_product_attention"): + attn_cls = SDPACrossAttention + else: + attn_cls = CrossAttention + + self.disable_self_attn = disable_self_attn + self.attn1 = attn_cls( + query_dim=dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + context_dim=context_dim if self.disable_self_attn else None, + ) # is a self-attention if not self.disable_self_attn + self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff) + self.attn2 = attn_cls( + query_dim=dim, + context_dim=context_dim, + heads=n_heads, + dim_head=d_head, + dropout=dropout, + ) # is self-attn if context is none + self.norm1 = nn.LayerNorm(dim) + self.norm2 = nn.LayerNorm(dim) + self.norm3 = nn.LayerNorm(dim) + self.checkpoint = checkpoint + + def forward(self, x, context=None): + return checkpoint( + self._forward, (x, context), self.parameters(), self.checkpoint + ) + + def _forward(self, x, context=None): + x = ( + self.attn1( + self.norm1(x), context=context if self.disable_self_attn else None + ) + + x + ) + x = self.attn2(self.norm2(x), context=context) + x + x = self.ff(self.norm3(x)) + x + return x + + +class SpatialTransformer(nn.Module): + """ + Transformer block for image-like data. + First, project the input (aka embedding) + and reshape to b, t, d. + Then apply standard transformer action. + Finally, reshape to image + NEW: use_linear for more efficiency instead of the 1x1 convs + """ + + def __init__( + self, + in_channels, + n_heads, + d_head, + depth=1, + dropout=0.0, + context_dim=None, + disable_self_attn=False, + use_linear=False, + use_checkpoint=True, + ): + super().__init__() + if exists(context_dim) and not isinstance(context_dim, list): + context_dim = [context_dim] + self.in_channels = in_channels + inner_dim = n_heads * d_head + self.norm = Normalize(in_channels) + if not use_linear: + self.proj_in = nn.Conv2d( + in_channels, inner_dim, kernel_size=1, stride=1, padding=0 + ) + else: + self.proj_in = nn.Linear(in_channels, inner_dim) + + self.transformer_blocks = nn.ModuleList( + [ + BasicTransformerBlock( + inner_dim, + n_heads, + d_head, + dropout=dropout, + context_dim=context_dim[d], + disable_self_attn=disable_self_attn, + checkpoint=use_checkpoint, + ) + for d in range(depth) + ] + ) + if not use_linear: + self.proj_out = zero_module( + nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0) + ) + else: + self.proj_out = zero_module(nn.Linear(in_channels, inner_dim)) + self.use_linear = use_linear + + def forward(self, x, context=None): + # note: if no context is given, cross-attention defaults to self-attention + if not isinstance(context, list): + context = [context] + b, c, h, w = x.shape + x_in = x + x = self.norm(x) + if not self.use_linear: + x = self.proj_in(x) + x = rearrange(x, "b c h w -> b (h w) c").contiguous() + if self.use_linear: + x = self.proj_in(x) + for i, block in enumerate(self.transformer_blocks): + x = block(x, context=context[i]) + if self.use_linear: + x = self.proj_out(x) + x = rearrange(x, "b (h w) c -> b c h w", h=h, w=w).contiguous() + if not self.use_linear: + x = self.proj_out(x) + return x + x_in diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/__init__.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py new file mode 100644 index 0000000..3472824 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/model.py @@ -0,0 +1,973 @@ +# pytorch_diffusion + derived encoder decoder +import math + +import numpy as np +import torch +import torch.nn as nn + + +def get_timestep_embedding(timesteps, embedding_dim): + """ + This matches the implementation in Denoising Diffusion Probabilistic Models: + From Fairseq. + Build sinusoidal embeddings. + This matches the implementation in tensor2tensor, but differs slightly + from the description in Section 3.5 of "Attention Is All You Need". + """ + assert len(timesteps.shape) == 1 + + half_dim = embedding_dim // 2 + emb = math.log(10000) / (half_dim - 1) + emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb) + emb = emb.to(device=timesteps.device) + emb = timesteps.float()[:, None] * emb[None, :] + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1) + if embedding_dim % 2 == 1: # zero pad + emb = torch.nn.functional.pad(emb, (0, 1, 0, 0)) + return emb + + +def nonlinearity(x): + # swish + return x * torch.sigmoid(x) + + +def Normalize(in_channels, num_groups=32): + return torch.nn.GroupNorm( + num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True + ) + + +class Upsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") + if self.with_conv: + x = self.conv(x) + return x + + +class Downsample(nn.Module): + def __init__(self, in_channels, with_conv): + super().__init__() + self.with_conv = with_conv + if self.with_conv: + # no asymmetric padding in torch conv, must do it ourselves + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=3, stride=2, padding=0 + ) + + def forward(self, x): + if self.with_conv: + pad = (0, 1, 0, 1) + x = torch.nn.functional.pad(x, pad, mode="constant", value=0) + x = self.conv(x) + else: + x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2) + return x + + +class ResnetBlock(nn.Module): + def __init__( + self, + *, + in_channels, + out_channels=None, + conv_shortcut=False, + dropout, + temb_channels=512, + ): + super().__init__() + self.in_channels = in_channels + out_channels = in_channels if out_channels is None else out_channels + self.out_channels = out_channels + self.use_conv_shortcut = conv_shortcut + + self.norm1 = Normalize(in_channels) + self.conv1 = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + if temb_channels > 0: + self.temb_proj = torch.nn.Linear(temb_channels, out_channels) + self.norm2 = Normalize(out_channels) + self.dropout = torch.nn.Dropout(dropout) + self.conv2 = torch.nn.Conv2d( + out_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + self.conv_shortcut = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + else: + self.nin_shortcut = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x, temb): + h = x + h = self.norm1(h) + h = nonlinearity(h) + h = self.conv1(h) + + if temb is not None: + h = h + self.temb_proj(nonlinearity(temb))[:, :, None, None] + + h = self.norm2(h) + h = nonlinearity(h) + h = self.dropout(h) + h = self.conv2(h) + + if self.in_channels != self.out_channels: + if self.use_conv_shortcut: + x = self.conv_shortcut(x) + else: + x = self.nin_shortcut(x) + + return x + h + + +class AttnBlock(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + q = q.reshape(b, c, h * w) + q = q.permute(0, 2, 1) # b,hw,c + k = k.reshape(b, c, h * w) # b,c,hw + w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j] + w_ = w_ * (int(c) ** (-0.5)) + w_ = torch.nn.functional.softmax(w_, dim=2) + + # attend to values + v = v.reshape(b, c, h * w) + w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q) + h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j] + h_ = h_.reshape(b, c, h, w) + + h_ = self.proj_out(h_) + + return x + h_ + + +class AttnBlock2_0(nn.Module): + def __init__(self, in_channels): + super().__init__() + self.in_channels = in_channels + + self.norm = Normalize(in_channels) + self.q = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.k = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.v = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + self.proj_out = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=1, stride=1, padding=0 + ) + + def forward(self, x): + h_ = x + h_ = self.norm(h_) + # output: [1, 512, 64, 64] + q = self.q(h_) + k = self.k(h_) + v = self.v(h_) + + # compute attention + b, c, h, w = q.shape + + # q = q.reshape(b, c, h * w).transpose() + # q = q.permute(0, 2, 1) # b,hw,c + # k = k.reshape(b, c, h * w) # b,c,hw + q = q.transpose(1, 2) + k = k.transpose(1, 2) + v = v.transpose(1, 2) + # (batch, num_heads, seq_len, head_dim) + hidden_states = torch.nn.functional.scaled_dot_product_attention( + q, k, v, attn_mask=None, dropout_p=0.0, is_causal=False + ) + hidden_states = hidden_states.transpose(1, 2) + hidden_states = hidden_states.to(q.dtype) + + h_ = self.proj_out(hidden_states) + + return x + h_ + + +def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None): + assert attn_type in [ + "vanilla", + "vanilla-xformers", + "memory-efficient-cross-attn", + "linear", + "none", + ], f"attn_type {attn_type} unknown" + assert attn_kwargs is None + if hasattr(torch.nn.functional, "scaled_dot_product_attention"): + # print(f"Using torch.nn.functional.scaled_dot_product_attention") + return AttnBlock2_0(in_channels) + return AttnBlock(in_channels) + + +class Model(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + use_timestep=True, + use_linear_attn=False, + attn_type="vanilla", + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = self.ch * 4 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + + self.use_timestep = use_timestep + if self.use_timestep: + # timestep embedding + self.temb = nn.Module() + self.temb.dense = nn.ModuleList( + [ + torch.nn.Linear(self.ch, self.temb_ch), + torch.nn.Linear(self.temb_ch, self.temb_ch), + ] + ) + + # downsampling + self.conv_in = torch.nn.Conv2d( + in_channels, self.ch, kernel_size=3, stride=1, padding=1 + ) + + curr_res = resolution + in_ch_mult = (1,) + tuple(ch_mult) + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = ch * in_ch_mult[i_level] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions - 1: + down.downsample = Downsample(block_in, resamp_with_conv) + curr_res = curr_res // 2 + self.down.append(down) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = ch * ch_mult[i_level] + skip_in = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + if i_block == self.num_res_blocks: + skip_in = ch * in_ch_mult[i_level] + block.append( + ResnetBlock( + in_channels=block_in + skip_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = Upsample(block_in, resamp_with_conv) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_ch, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x, t=None, context=None): + # assert x.shape[2] == x.shape[3] == self.resolution + if context is not None: + # assume aligned context, cat along channel axis + x = torch.cat((x, context), dim=1) + if self.use_timestep: + # timestep embedding + assert t is not None + temb = get_timestep_embedding(t, self.ch) + temb = self.temb.dense[0](temb) + temb = nonlinearity(temb) + temb = self.temb.dense[1](temb) + else: + temb = None + + # downsampling + hs = [self.conv_in(x)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + h = self.down[i_level].block[i_block](hs[-1], temb) + if len(self.down[i_level].attn) > 0: + h = self.down[i_level].attn[i_block](h) + hs.append(h) + if i_level != self.num_resolutions - 1: + hs.append(self.down[i_level].downsample(hs[-1])) + + # middle + h = hs[-1] + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.up[i_level].block[i_block]( + torch.cat([h, hs.pop()], dim=1), temb + ) + if len(self.up[i_level].attn) > 0: + h = self.up[i_level].attn[i_block](h) + if i_level != 0: + h = self.up[i_level].upsample(h) + + # end + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + def get_last_layer(self): + return self.conv_out.weight + + +class Encoder(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + z_channels, + double_z=True, + use_linear_attn=False, + attn_type="vanilla", + **ignore_kwargs, + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + + # downsampling + self.conv_in = torch.nn.Conv2d( + in_channels, self.ch, kernel_size=3, stride=1, padding=1 + ) + + curr_res = resolution + in_ch_mult = (1,) + tuple(ch_mult) + self.in_ch_mult = in_ch_mult + self.down = nn.ModuleList() + for i_level in range(self.num_resolutions): + block = nn.ModuleList() + attn = nn.ModuleList() + block_in = ch * in_ch_mult[i_level] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + down = nn.Module() + down.block = block + down.attn = attn + if i_level != self.num_resolutions - 1: + down.downsample = Downsample(block_in, resamp_with_conv) + curr_res = curr_res // 2 + self.down.append(down) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, + 2 * z_channels if double_z else z_channels, + kernel_size=3, + stride=1, + padding=1, + ) + + def forward(self, x): + # timestep embedding + temb = None + + # downsampling + hs = [self.conv_in(x)] + for i_level in range(self.num_resolutions): + for i_block in range(self.num_res_blocks): + h = self.down[i_level].block[i_block](hs[-1], temb) + if len(self.down[i_level].attn) > 0: + h = self.down[i_level].attn[i_block](h) + hs.append(h) + if i_level != self.num_resolutions - 1: + hs.append(self.down[i_level].downsample(hs[-1])) + + # middle + h = hs[-1] + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # end + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class Decoder(nn.Module): + def __init__( + self, + *, + ch, + out_ch, + ch_mult=(1, 2, 4, 8), + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + in_channels, + resolution, + z_channels, + give_pre_end=False, + tanh_out=False, + use_linear_attn=False, + attn_type="vanilla", + **ignorekwargs, + ): + super().__init__() + if use_linear_attn: + attn_type = "linear" + self.ch = ch + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + self.resolution = resolution + self.in_channels = in_channels + self.give_pre_end = give_pre_end + self.tanh_out = tanh_out + + # compute in_ch_mult, block_in and curr_res at lowest res + in_ch_mult = (1,) + tuple(ch_mult) + block_in = ch * ch_mult[self.num_resolutions - 1] + curr_res = resolution // 2 ** (self.num_resolutions - 1) + self.z_shape = (1, z_channels, curr_res, curr_res) + print( + "Working with z of shape {} = {} dimensions.".format( + self.z_shape, np.prod(self.z_shape) + ) + ) + + # z to block_in + self.conv_in = torch.nn.Conv2d( + z_channels, block_in, kernel_size=3, stride=1, padding=1 + ) + + # middle + self.mid = nn.Module() + self.mid.block_1 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + self.mid.attn_1 = make_attn(block_in, attn_type=attn_type) + self.mid.block_2 = ResnetBlock( + in_channels=block_in, + out_channels=block_in, + temb_channels=self.temb_ch, + dropout=dropout, + ) + + # upsampling + self.up = nn.ModuleList() + for i_level in reversed(range(self.num_resolutions)): + block = nn.ModuleList() + attn = nn.ModuleList() + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + if curr_res in attn_resolutions: + attn.append(make_attn(block_in, attn_type=attn_type)) + up = nn.Module() + up.block = block + up.attn = attn + if i_level != 0: + up.upsample = Upsample(block_in, resamp_with_conv) + curr_res = curr_res * 2 + self.up.insert(0, up) # prepend to get consistent order + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_ch, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, z): + # assert z.shape[1:] == self.z_shape[1:] + self.last_z_shape = z.shape + + # timestep embedding + temb = None + + # z to block_in + h = self.conv_in(z) + + # middle + h = self.mid.block_1(h, temb) + h = self.mid.attn_1(h) + h = self.mid.block_2(h, temb) + + # upsampling + for i_level in reversed(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.up[i_level].block[i_block](h, temb) + if len(self.up[i_level].attn) > 0: + h = self.up[i_level].attn[i_block](h) + if i_level != 0: + h = self.up[i_level].upsample(h) + + # end + if self.give_pre_end: + return h + + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + if self.tanh_out: + h = torch.tanh(h) + return h + + +class SimpleDecoder(nn.Module): + def __init__(self, in_channels, out_channels, *args, **kwargs): + super().__init__() + self.model = nn.ModuleList( + [ + nn.Conv2d(in_channels, in_channels, 1), + ResnetBlock( + in_channels=in_channels, + out_channels=2 * in_channels, + temb_channels=0, + dropout=0.0, + ), + ResnetBlock( + in_channels=2 * in_channels, + out_channels=4 * in_channels, + temb_channels=0, + dropout=0.0, + ), + ResnetBlock( + in_channels=4 * in_channels, + out_channels=2 * in_channels, + temb_channels=0, + dropout=0.0, + ), + nn.Conv2d(2 * in_channels, in_channels, 1), + Upsample(in_channels, with_conv=True), + ] + ) + # end + self.norm_out = Normalize(in_channels) + self.conv_out = torch.nn.Conv2d( + in_channels, out_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + for i, layer in enumerate(self.model): + if i in [1, 2, 3]: + x = layer(x, None) + else: + x = layer(x) + + h = self.norm_out(x) + h = nonlinearity(h) + x = self.conv_out(h) + return x + + +class UpsampleDecoder(nn.Module): + def __init__( + self, + in_channels, + out_channels, + ch, + num_res_blocks, + resolution, + ch_mult=(2, 2), + dropout=0.0, + ): + super().__init__() + # upsampling + self.temb_ch = 0 + self.num_resolutions = len(ch_mult) + self.num_res_blocks = num_res_blocks + block_in = in_channels + curr_res = resolution // 2 ** (self.num_resolutions - 1) + self.res_blocks = nn.ModuleList() + self.upsample_blocks = nn.ModuleList() + for i_level in range(self.num_resolutions): + res_block = [] + block_out = ch * ch_mult[i_level] + for i_block in range(self.num_res_blocks + 1): + res_block.append( + ResnetBlock( + in_channels=block_in, + out_channels=block_out, + temb_channels=self.temb_ch, + dropout=dropout, + ) + ) + block_in = block_out + self.res_blocks.append(nn.ModuleList(res_block)) + if i_level != self.num_resolutions - 1: + self.upsample_blocks.append(Upsample(block_in, True)) + curr_res = curr_res * 2 + + # end + self.norm_out = Normalize(block_in) + self.conv_out = torch.nn.Conv2d( + block_in, out_channels, kernel_size=3, stride=1, padding=1 + ) + + def forward(self, x): + # upsampling + h = x + for k, i_level in enumerate(range(self.num_resolutions)): + for i_block in range(self.num_res_blocks + 1): + h = self.res_blocks[i_level][i_block](h, None) + if i_level != self.num_resolutions - 1: + h = self.upsample_blocks[k](h) + h = self.norm_out(h) + h = nonlinearity(h) + h = self.conv_out(h) + return h + + +class LatentRescaler(nn.Module): + def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2): + super().__init__() + # residual block, interpolate, residual block + self.factor = factor + self.conv_in = nn.Conv2d( + in_channels, mid_channels, kernel_size=3, stride=1, padding=1 + ) + self.res_block1 = nn.ModuleList( + [ + ResnetBlock( + in_channels=mid_channels, + out_channels=mid_channels, + temb_channels=0, + dropout=0.0, + ) + for _ in range(depth) + ] + ) + self.attn = AttnBlock(mid_channels) + self.res_block2 = nn.ModuleList( + [ + ResnetBlock( + in_channels=mid_channels, + out_channels=mid_channels, + temb_channels=0, + dropout=0.0, + ) + for _ in range(depth) + ] + ) + + self.conv_out = nn.Conv2d( + mid_channels, + out_channels, + kernel_size=1, + ) + + def forward(self, x): + x = self.conv_in(x) + for block in self.res_block1: + x = block(x, None) + x = torch.nn.functional.interpolate( + x, + size=( + int(round(x.shape[2] * self.factor)), + int(round(x.shape[3] * self.factor)), + ), + ) + x = self.attn(x) + for block in self.res_block2: + x = block(x, None) + x = self.conv_out(x) + return x + + +class MergedRescaleEncoder(nn.Module): + def __init__( + self, + in_channels, + ch, + resolution, + out_ch, + num_res_blocks, + attn_resolutions, + dropout=0.0, + resamp_with_conv=True, + ch_mult=(1, 2, 4, 8), + rescale_factor=1.0, + rescale_module_depth=1, + ): + super().__init__() + intermediate_chn = ch * ch_mult[-1] + self.encoder = Encoder( + in_channels=in_channels, + num_res_blocks=num_res_blocks, + ch=ch, + ch_mult=ch_mult, + z_channels=intermediate_chn, + double_z=False, + resolution=resolution, + attn_resolutions=attn_resolutions, + dropout=dropout, + resamp_with_conv=resamp_with_conv, + out_ch=None, + ) + self.rescaler = LatentRescaler( + factor=rescale_factor, + in_channels=intermediate_chn, + mid_channels=intermediate_chn, + out_channels=out_ch, + depth=rescale_module_depth, + ) + + def forward(self, x): + x = self.encoder(x) + x = self.rescaler(x) + return x + + +class MergedRescaleDecoder(nn.Module): + def __init__( + self, + z_channels, + out_ch, + resolution, + num_res_blocks, + attn_resolutions, + ch, + ch_mult=(1, 2, 4, 8), + dropout=0.0, + resamp_with_conv=True, + rescale_factor=1.0, + rescale_module_depth=1, + ): + super().__init__() + tmp_chn = z_channels * ch_mult[-1] + self.decoder = Decoder( + out_ch=out_ch, + z_channels=tmp_chn, + attn_resolutions=attn_resolutions, + dropout=dropout, + resamp_with_conv=resamp_with_conv, + in_channels=None, + num_res_blocks=num_res_blocks, + ch_mult=ch_mult, + resolution=resolution, + ch=ch, + ) + self.rescaler = LatentRescaler( + factor=rescale_factor, + in_channels=z_channels, + mid_channels=tmp_chn, + out_channels=tmp_chn, + depth=rescale_module_depth, + ) + + def forward(self, x): + x = self.rescaler(x) + x = self.decoder(x) + return x + + +class Upsampler(nn.Module): + def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2): + super().__init__() + assert out_size >= in_size + num_blocks = int(np.log2(out_size // in_size)) + 1 + factor_up = 1.0 + (out_size % in_size) + print( + f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}" + ) + self.rescaler = LatentRescaler( + factor=factor_up, + in_channels=in_channels, + mid_channels=2 * in_channels, + out_channels=in_channels, + ) + self.decoder = Decoder( + out_ch=out_channels, + resolution=out_size, + z_channels=in_channels, + num_res_blocks=2, + attn_resolutions=[], + in_channels=None, + ch=in_channels, + ch_mult=[ch_mult for _ in range(num_blocks)], + ) + + def forward(self, x): + x = self.rescaler(x) + x = self.decoder(x) + return x + + +class Resize(nn.Module): + def __init__(self, in_channels=None, learned=False, mode="bilinear"): + super().__init__() + self.with_conv = learned + self.mode = mode + if self.with_conv: + print( + f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode" + ) + raise NotImplementedError() + assert in_channels is not None + # no asymmetric padding in torch conv, must do it ourselves + self.conv = torch.nn.Conv2d( + in_channels, in_channels, kernel_size=4, stride=2, padding=1 + ) + + def forward(self, x, scale_factor=1.0): + if scale_factor == 1.0: + return x + else: + x = torch.nn.functional.interpolate( + x, mode=self.mode, align_corners=False, scale_factor=scale_factor + ) + return x diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py new file mode 100644 index 0000000..fd3d6be --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/openaimodel.py @@ -0,0 +1,786 @@ +from abc import abstractmethod +import math + +import numpy as np +import torch as th +import torch.nn as nn +import torch.nn.functional as F + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import ( + checkpoint, + conv_nd, + linear, + avg_pool_nd, + zero_module, + normalization, + timestep_embedding, +) +from iopaint.model.anytext.ldm.modules.attention import SpatialTransformer +from iopaint.model.anytext.ldm.util import exists + + +# dummy replace +def convert_module_to_f16(x): + pass + +def convert_module_to_f32(x): + pass + + +## go +class AttentionPool2d(nn.Module): + """ + Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py + """ + + def __init__( + self, + spacial_dim: int, + embed_dim: int, + num_heads_channels: int, + output_dim: int = None, + ): + super().__init__() + self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5) + self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) + self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) + self.num_heads = embed_dim // num_heads_channels + self.attention = QKVAttention(self.num_heads) + + def forward(self, x): + b, c, *_spatial = x.shape + x = x.reshape(b, c, -1) # NC(HW) + x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) + x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) + x = self.qkv_proj(x) + x = self.attention(x) + x = self.c_proj(x) + return x[:, :, 0] + + +class TimestepBlock(nn.Module): + """ + Any module where forward() takes timestep embeddings as a second argument. + """ + + @abstractmethod + def forward(self, x, emb): + """ + Apply the module to `x` given `emb` timestep embeddings. + """ + + +class TimestepEmbedSequential(nn.Sequential, TimestepBlock): + """ + A sequential module that passes timestep embeddings to the children that + support it as an extra input. + """ + + def forward(self, x, emb, context=None): + for layer in self: + if isinstance(layer, TimestepBlock): + x = layer(x, emb) + elif isinstance(layer, SpatialTransformer): + x = layer(x, context) + else: + x = layer(x) + return x + + +class Upsample(nn.Module): + """ + An upsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + upsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + if use_conv: + self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding) + + def forward(self, x): + assert x.shape[1] == self.channels + if self.dims == 3: + x = F.interpolate( + x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" + ) + else: + x = F.interpolate(x, scale_factor=2, mode="nearest") + if self.use_conv: + x = self.conv(x) + return x + +class TransposedUpsample(nn.Module): + 'Learned 2x upsampling without padding' + def __init__(self, channels, out_channels=None, ks=5): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + + self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2) + + def forward(self,x): + return self.up(x) + + +class Downsample(nn.Module): + """ + A downsampling layer with an optional convolution. + :param channels: channels in the inputs and outputs. + :param use_conv: a bool determining if a convolution is applied. + :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then + downsampling occurs in the inner-two dimensions. + """ + + def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1): + super().__init__() + self.channels = channels + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.dims = dims + stride = 2 if dims != 3 else (1, 2, 2) + if use_conv: + self.op = conv_nd( + dims, self.channels, self.out_channels, 3, stride=stride, padding=padding + ) + else: + assert self.channels == self.out_channels + self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) + + def forward(self, x): + assert x.shape[1] == self.channels + return self.op(x) + + +class ResBlock(TimestepBlock): + """ + A residual block that can optionally change the number of channels. + :param channels: the number of input channels. + :param emb_channels: the number of timestep embedding channels. + :param dropout: the rate of dropout. + :param out_channels: if specified, the number of out channels. + :param use_conv: if True and out_channels is specified, use a spatial + convolution instead of a smaller 1x1 convolution to change the + channels in the skip connection. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param use_checkpoint: if True, use gradient checkpointing on this module. + :param up: if True, use this block for upsampling. + :param down: if True, use this block for downsampling. + """ + + def __init__( + self, + channels, + emb_channels, + dropout, + out_channels=None, + use_conv=False, + use_scale_shift_norm=False, + dims=2, + use_checkpoint=False, + up=False, + down=False, + ): + super().__init__() + self.channels = channels + self.emb_channels = emb_channels + self.dropout = dropout + self.out_channels = out_channels or channels + self.use_conv = use_conv + self.use_checkpoint = use_checkpoint + self.use_scale_shift_norm = use_scale_shift_norm + + self.in_layers = nn.Sequential( + normalization(channels), + nn.SiLU(), + conv_nd(dims, channels, self.out_channels, 3, padding=1), + ) + + self.updown = up or down + + if up: + self.h_upd = Upsample(channels, False, dims) + self.x_upd = Upsample(channels, False, dims) + elif down: + self.h_upd = Downsample(channels, False, dims) + self.x_upd = Downsample(channels, False, dims) + else: + self.h_upd = self.x_upd = nn.Identity() + + self.emb_layers = nn.Sequential( + nn.SiLU(), + linear( + emb_channels, + 2 * self.out_channels if use_scale_shift_norm else self.out_channels, + ), + ) + self.out_layers = nn.Sequential( + normalization(self.out_channels), + nn.SiLU(), + nn.Dropout(p=dropout), + zero_module( + conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1) + ), + ) + + if self.out_channels == channels: + self.skip_connection = nn.Identity() + elif use_conv: + self.skip_connection = conv_nd( + dims, channels, self.out_channels, 3, padding=1 + ) + else: + self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) + + def forward(self, x, emb): + """ + Apply the block to a Tensor, conditioned on a timestep embedding. + :param x: an [N x C x ...] Tensor of features. + :param emb: an [N x emb_channels] Tensor of timestep embeddings. + :return: an [N x C x ...] Tensor of outputs. + """ + return checkpoint( + self._forward, (x, emb), self.parameters(), self.use_checkpoint + ) + + + def _forward(self, x, emb): + if self.updown: + in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] + h = in_rest(x) + h = self.h_upd(h) + x = self.x_upd(x) + h = in_conv(h) + else: + h = self.in_layers(x) + emb_out = self.emb_layers(emb).type(h.dtype) + while len(emb_out.shape) < len(h.shape): + emb_out = emb_out[..., None] + if self.use_scale_shift_norm: + out_norm, out_rest = self.out_layers[0], self.out_layers[1:] + scale, shift = th.chunk(emb_out, 2, dim=1) + h = out_norm(h) * (1 + scale) + shift + h = out_rest(h) + else: + h = h + emb_out + h = self.out_layers(h) + return self.skip_connection(x) + h + + +class AttentionBlock(nn.Module): + """ + An attention block that allows spatial positions to attend to each other. + Originally ported from here, but adapted to the N-d case. + https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. + """ + + def __init__( + self, + channels, + num_heads=1, + num_head_channels=-1, + use_checkpoint=False, + use_new_attention_order=False, + ): + super().__init__() + self.channels = channels + if num_head_channels == -1: + self.num_heads = num_heads + else: + assert ( + channels % num_head_channels == 0 + ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" + self.num_heads = channels // num_head_channels + self.use_checkpoint = use_checkpoint + self.norm = normalization(channels) + self.qkv = conv_nd(1, channels, channels * 3, 1) + if use_new_attention_order: + # split qkv before split heads + self.attention = QKVAttention(self.num_heads) + else: + # split heads before split qkv + self.attention = QKVAttentionLegacy(self.num_heads) + + self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) + + def forward(self, x): + return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!! + #return pt_checkpoint(self._forward, x) # pytorch + + def _forward(self, x): + b, c, *spatial = x.shape + x = x.reshape(b, c, -1) + qkv = self.qkv(self.norm(x)) + h = self.attention(qkv) + h = self.proj_out(h) + return (x + h).reshape(b, c, *spatial) + + +def count_flops_attn(model, _x, y): + """ + A counter for the `thop` package to count the operations in an + attention operation. + Meant to be used like: + macs, params = thop.profile( + model, + inputs=(inputs, timestamps), + custom_ops={QKVAttention: QKVAttention.count_flops}, + ) + """ + b, c, *spatial = y[0].shape + num_spatial = int(np.prod(spatial)) + # We perform two matmuls with the same number of ops. + # The first computes the weight matrix, the second computes + # the combination of the value vectors. + matmul_ops = 2 * b * (num_spatial ** 2) * c + model.total_ops += th.DoubleTensor([matmul_ops]) + + +class QKVAttentionLegacy(nn.Module): + """ + A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping + """ + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """ + Apply QKV attention. + :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", q * scale, k * scale + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class QKVAttention(nn.Module): + """ + A module which performs QKV attention and splits in a different order. + """ + + def __init__(self, n_heads): + super().__init__() + self.n_heads = n_heads + + def forward(self, qkv): + """ + Apply QKV attention. + :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. + :return: an [N x (H * C) x T] tensor after attention. + """ + bs, width, length = qkv.shape + assert width % (3 * self.n_heads) == 0 + ch = width // (3 * self.n_heads) + q, k, v = qkv.chunk(3, dim=1) + scale = 1 / math.sqrt(math.sqrt(ch)) + weight = th.einsum( + "bct,bcs->bts", + (q * scale).view(bs * self.n_heads, ch, length), + (k * scale).view(bs * self.n_heads, ch, length), + ) # More stable with f16 than dividing afterwards + weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) + a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) + return a.reshape(bs, -1, length) + + @staticmethod + def count_flops(model, _x, y): + return count_flops_attn(model, _x, y) + + +class UNetModel(nn.Module): + """ + The full UNet model with attention and timestep embedding. + :param in_channels: channels in the input Tensor. + :param model_channels: base channel count for the model. + :param out_channels: channels in the output Tensor. + :param num_res_blocks: number of residual blocks per downsample. + :param attention_resolutions: a collection of downsample rates at which + attention will take place. May be a set, list, or tuple. + For example, if this contains 4, then at 4x downsampling, attention + will be used. + :param dropout: the dropout probability. + :param channel_mult: channel multiplier for each level of the UNet. + :param conv_resample: if True, use learned convolutions for upsampling and + downsampling. + :param dims: determines if the signal is 1D, 2D, or 3D. + :param num_classes: if specified (as an int), then this model will be + class-conditional with `num_classes` classes. + :param use_checkpoint: use gradient checkpointing to reduce memory usage. + :param num_heads: the number of attention heads in each attention layer. + :param num_heads_channels: if specified, ignore num_heads and instead use + a fixed channel width per attention head. + :param num_heads_upsample: works with num_heads to set a different number + of heads for upsampling. Deprecated. + :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. + :param resblock_updown: use residual blocks for up/downsampling. + :param use_new_attention_order: use a different attention pattern for potentially + increased efficiency. + """ + + def __init__( + self, + image_size, + in_channels, + model_channels, + out_channels, + num_res_blocks, + attention_resolutions, + dropout=0, + channel_mult=(1, 2, 4, 8), + conv_resample=True, + dims=2, + num_classes=None, + use_checkpoint=False, + use_fp16=False, + num_heads=-1, + num_head_channels=-1, + num_heads_upsample=-1, + use_scale_shift_norm=False, + resblock_updown=False, + use_new_attention_order=False, + use_spatial_transformer=False, # custom transformer support + transformer_depth=1, # custom transformer support + context_dim=None, # custom transformer support + n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model + legacy=True, + disable_self_attentions=None, + num_attention_blocks=None, + disable_middle_self_attn=False, + use_linear_in_transformer=False, + ): + super().__init__() + if use_spatial_transformer: + assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...' + + if context_dim is not None: + assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...' + from omegaconf.listconfig import ListConfig + if type(context_dim) == ListConfig: + context_dim = list(context_dim) + + if num_heads_upsample == -1: + num_heads_upsample = num_heads + + if num_heads == -1: + assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set' + + if num_head_channels == -1: + assert num_heads != -1, 'Either num_heads or num_head_channels has to be set' + + self.image_size = image_size + self.in_channels = in_channels + self.model_channels = model_channels + self.out_channels = out_channels + if isinstance(num_res_blocks, int): + self.num_res_blocks = len(channel_mult) * [num_res_blocks] + else: + if len(num_res_blocks) != len(channel_mult): + raise ValueError("provide num_res_blocks either as an int (globally constant) or " + "as a list/tuple (per-level) with the same length as channel_mult") + self.num_res_blocks = num_res_blocks + if disable_self_attentions is not None: + # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not + assert len(disable_self_attentions) == len(channel_mult) + if num_attention_blocks is not None: + assert len(num_attention_blocks) == len(self.num_res_blocks) + assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks)))) + print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. " + f"This option has LESS priority than attention_resolutions {attention_resolutions}, " + f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, " + f"attention will still not be set.") + self.use_fp16 = use_fp16 + self.attention_resolutions = attention_resolutions + self.dropout = dropout + self.channel_mult = channel_mult + self.conv_resample = conv_resample + self.num_classes = num_classes + self.use_checkpoint = use_checkpoint + self.dtype = th.float16 if use_fp16 else th.float32 + self.num_heads = num_heads + self.num_head_channels = num_head_channels + self.num_heads_upsample = num_heads_upsample + self.predict_codebook_ids = n_embed is not None + + time_embed_dim = model_channels * 4 + self.time_embed = nn.Sequential( + linear(model_channels, time_embed_dim), + nn.SiLU(), + linear(time_embed_dim, time_embed_dim), + ) + + if self.num_classes is not None: + if isinstance(self.num_classes, int): + self.label_emb = nn.Embedding(num_classes, time_embed_dim) + elif self.num_classes == "continuous": + print("setting up linear c_adm embedding layer") + self.label_emb = nn.Linear(1, time_embed_dim) + else: + raise ValueError() + + self.input_blocks = nn.ModuleList( + [ + TimestepEmbedSequential( + conv_nd(dims, in_channels, model_channels, 3, padding=1) + ) + ] + ) + self._feature_size = model_channels + input_block_chans = [model_channels] + ch = model_channels + ds = 1 + for level, mult in enumerate(channel_mult): + for nr in range(self.num_res_blocks[level]): + layers = [ + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=mult * model_channels, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = mult * model_channels + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or nr < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + self.input_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + input_block_chans.append(ch) + if level != len(channel_mult) - 1: + out_ch = ch + self.input_blocks.append( + TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + down=True, + ) + if resblock_updown + else Downsample( + ch, conv_resample, dims=dims, out_channels=out_ch + ) + ) + ) + ch = out_ch + input_block_chans.append(ch) + ds *= 2 + self._feature_size += ch + + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + self.middle_block = TimestepEmbedSequential( + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ), + ResBlock( + ch, + time_embed_dim, + dropout, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ), + ) + self._feature_size += ch + + self.output_blocks = nn.ModuleList([]) + for level, mult in list(enumerate(channel_mult))[::-1]: + for i in range(self.num_res_blocks[level] + 1): + ich = input_block_chans.pop() + layers = [ + ResBlock( + ch + ich, + time_embed_dim, + dropout, + out_channels=model_channels * mult, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + ) + ] + ch = model_channels * mult + if ds in attention_resolutions: + if num_head_channels == -1: + dim_head = ch // num_heads + else: + num_heads = ch // num_head_channels + dim_head = num_head_channels + if legacy: + #num_heads = 1 + dim_head = ch // num_heads if use_spatial_transformer else num_head_channels + if exists(disable_self_attentions): + disabled_sa = disable_self_attentions[level] + else: + disabled_sa = False + + if not exists(num_attention_blocks) or i < num_attention_blocks[level]: + layers.append( + AttentionBlock( + ch, + use_checkpoint=use_checkpoint, + num_heads=num_heads_upsample, + num_head_channels=dim_head, + use_new_attention_order=use_new_attention_order, + ) if not use_spatial_transformer else SpatialTransformer( + ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim, + disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer, + use_checkpoint=use_checkpoint + ) + ) + if level and i == self.num_res_blocks[level]: + out_ch = ch + layers.append( + ResBlock( + ch, + time_embed_dim, + dropout, + out_channels=out_ch, + dims=dims, + use_checkpoint=use_checkpoint, + use_scale_shift_norm=use_scale_shift_norm, + up=True, + ) + if resblock_updown + else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) + ) + ds //= 2 + self.output_blocks.append(TimestepEmbedSequential(*layers)) + self._feature_size += ch + + self.out = nn.Sequential( + normalization(ch), + nn.SiLU(), + zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)), + ) + if self.predict_codebook_ids: + self.id_predictor = nn.Sequential( + normalization(ch), + conv_nd(dims, model_channels, n_embed, 1), + #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits + ) + + def convert_to_fp16(self): + """ + Convert the torso of the model to float16. + """ + self.input_blocks.apply(convert_module_to_f16) + self.middle_block.apply(convert_module_to_f16) + self.output_blocks.apply(convert_module_to_f16) + + def convert_to_fp32(self): + """ + Convert the torso of the model to float32. + """ + self.input_blocks.apply(convert_module_to_f32) + self.middle_block.apply(convert_module_to_f32) + self.output_blocks.apply(convert_module_to_f32) + + def forward(self, x, timesteps=None, context=None, y=None,**kwargs): + """ + Apply the model to an input batch. + :param x: an [N x C x ...] Tensor of inputs. + :param timesteps: a 1-D batch of timesteps. + :param context: conditioning plugged in via crossattn + :param y: an [N] Tensor of labels, if class-conditional. + :return: an [N x C x ...] Tensor of outputs. + """ + assert (y is not None) == ( + self.num_classes is not None + ), "must specify y if and only if the model is class-conditional" + hs = [] + t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False) + emb = self.time_embed(t_emb) + + if self.num_classes is not None: + assert y.shape[0] == x.shape[0] + emb = emb + self.label_emb(y) + + h = x.type(self.dtype) + for module in self.input_blocks: + h = module(h, emb, context) + hs.append(h) + h = self.middle_block(h, emb, context) + for module in self.output_blocks: + h = th.cat([h, hs.pop()], dim=1) + h = module(h, emb, context) + h = h.type(x.dtype) + if self.predict_codebook_ids: + return self.id_predictor(h) + else: + return self.out(h) diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py new file mode 100644 index 0000000..5f92630 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/upscaling.py @@ -0,0 +1,81 @@ +import torch +import torch.nn as nn +import numpy as np +from functools import partial + +from iopaint.model.anytext.ldm.modules.diffusionmodules.util import extract_into_tensor, make_beta_schedule +from iopaint.model.anytext.ldm.util import default + + +class AbstractLowScaleModel(nn.Module): + # for concatenating a downsampled image to the latent representation + def __init__(self, noise_schedule_config=None): + super(AbstractLowScaleModel, self).__init__() + if noise_schedule_config is not None: + self.register_schedule(**noise_schedule_config) + + def register_schedule(self, beta_schedule="linear", timesteps=1000, + linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): + betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end, + cosine_s=cosine_s) + alphas = 1. - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1]) + + timesteps, = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep' + + to_torch = partial(torch.tensor, dtype=torch.float32) + + self.register_buffer('betas', to_torch(betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1))) + + def q_sample(self, x_start, t, noise=None): + noise = default(noise, lambda: torch.randn_like(x_start)) + return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + + extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise) + + def forward(self, x): + return x, None + + def decode(self, x): + return x + + +class SimpleImageConcat(AbstractLowScaleModel): + # no noise level conditioning + def __init__(self): + super(SimpleImageConcat, self).__init__(noise_schedule_config=None) + self.max_noise_level = 0 + + def forward(self, x): + # fix to constant noise level + return x, torch.zeros(x.shape[0], device=x.device).long() + + +class ImageConcatWithNoiseAugmentation(AbstractLowScaleModel): + def __init__(self, noise_schedule_config, max_noise_level=1000, to_cuda=False): + super().__init__(noise_schedule_config=noise_schedule_config) + self.max_noise_level = max_noise_level + + def forward(self, x, noise_level=None): + if noise_level is None: + noise_level = torch.randint(0, self.max_noise_level, (x.shape[0],), device=x.device).long() + else: + assert isinstance(noise_level, torch.Tensor) + z = self.q_sample(x, noise_level) + return z, noise_level + + + diff --git a/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py new file mode 100644 index 0000000..da29c72 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/diffusionmodules/util.py @@ -0,0 +1,271 @@ +# adopted from +# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py +# and +# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py +# and +# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py +# +# thanks! + + +import os +import math +import torch +import torch.nn as nn +import numpy as np +from einops import repeat + +from iopaint.model.anytext.ldm.util import instantiate_from_config + + +def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3): + if schedule == "linear": + betas = ( + torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2 + ) + + elif schedule == "cosine": + timesteps = ( + torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s + ) + alphas = timesteps / (1 + cosine_s) * np.pi / 2 + alphas = torch.cos(alphas).pow(2) + alphas = alphas / alphas[0] + betas = 1 - alphas[1:] / alphas[:-1] + betas = np.clip(betas, a_min=0, a_max=0.999) + + elif schedule == "sqrt_linear": + betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) + elif schedule == "sqrt": + betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5 + else: + raise ValueError(f"schedule '{schedule}' unknown.") + return betas.numpy() + + +def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True): + if ddim_discr_method == 'uniform': + c = num_ddpm_timesteps // num_ddim_timesteps + ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) + elif ddim_discr_method == 'quad': + ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int) + else: + raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"') + + # assert ddim_timesteps.shape[0] == num_ddim_timesteps + # add one to get the final alpha values right (the ones from first scale to data during sampling) + steps_out = ddim_timesteps + 1 + if verbose: + print(f'Selected timesteps for ddim sampler: {steps_out}') + return steps_out + + +def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): + # select alphas for computing the variance schedule + alphas = alphacums[ddim_timesteps] + alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) + + # according the the formula provided in https://arxiv.org/abs/2010.02502 + sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev)) + if verbose: + print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}') + print(f'For the chosen value of eta, which is {eta}, ' + f'this results in the following sigma_t schedule for ddim sampler {sigmas}') + return sigmas.to(torch.float32), alphas.to(torch.float32), alphas_prev.astype(np.float32) + + +def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): + """ + Create a beta schedule that discretizes the given alpha_t_bar function, + which defines the cumulative product of (1-beta) over time from t = [0,1]. + :param num_diffusion_timesteps: the number of betas to produce. + :param alpha_bar: a lambda that takes an argument t from 0 to 1 and + produces the cumulative product of (1-beta) up to that + part of the diffusion process. + :param max_beta: the maximum beta to use; use values lower than 1 to + prevent singularities. + """ + betas = [] + for i in range(num_diffusion_timesteps): + t1 = i / num_diffusion_timesteps + t2 = (i + 1) / num_diffusion_timesteps + betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) + return np.array(betas) + + +def extract_into_tensor(a, t, x_shape): + b, *_ = t.shape + out = a.gather(-1, t) + return out.reshape(b, *((1,) * (len(x_shape) - 1))) + + +def checkpoint(func, inputs, params, flag): + """ + Evaluate a function without caching intermediate activations, allowing for + reduced memory at the expense of extra compute in the backward pass. + :param func: the function to evaluate. + :param inputs: the argument sequence to pass to `func`. + :param params: a sequence of parameters `func` depends on but does not + explicitly take as arguments. + :param flag: if False, disable gradient checkpointing. + """ + if flag: + args = tuple(inputs) + tuple(params) + return CheckpointFunction.apply(func, len(inputs), *args) + else: + return func(*inputs) + + +class CheckpointFunction(torch.autograd.Function): + @staticmethod + def forward(ctx, run_function, length, *args): + ctx.run_function = run_function + ctx.input_tensors = list(args[:length]) + ctx.input_params = list(args[length:]) + ctx.gpu_autocast_kwargs = {"enabled": torch.is_autocast_enabled(), + "dtype": torch.get_autocast_gpu_dtype(), + "cache_enabled": torch.is_autocast_cache_enabled()} + with torch.no_grad(): + output_tensors = ctx.run_function(*ctx.input_tensors) + return output_tensors + + @staticmethod + def backward(ctx, *output_grads): + ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] + with torch.enable_grad(), \ + torch.cuda.amp.autocast(**ctx.gpu_autocast_kwargs): + # Fixes a bug where the first op in run_function modifies the + # Tensor storage in place, which is not allowed for detach()'d + # Tensors. + shallow_copies = [x.view_as(x) for x in ctx.input_tensors] + output_tensors = ctx.run_function(*shallow_copies) + input_grads = torch.autograd.grad( + output_tensors, + ctx.input_tensors + ctx.input_params, + output_grads, + allow_unused=True, + ) + del ctx.input_tensors + del ctx.input_params + del output_tensors + return (None, None) + input_grads + + +def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + if not repeat_only: + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half + ).to(device=timesteps.device) + args = timesteps[:, None].float() * freqs[None] + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + else: + embedding = repeat(timesteps, 'b -> b d', d=dim) + return embedding + + +def zero_module(module): + """ + Zero out the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().zero_() + return module + + +def scale_module(module, scale): + """ + Scale the parameters of a module and return it. + """ + for p in module.parameters(): + p.detach().mul_(scale) + return module + + +def mean_flat(tensor): + """ + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +def normalization(channels): + """ + Make a standard normalization layer. + :param channels: number of input channels. + :return: an nn.Module for normalization. + """ + return GroupNorm32(32, channels) + + +# PyTorch 1.7 has SiLU, but we support PyTorch 1.5. +class SiLU(nn.Module): + def forward(self, x): + return x * torch.sigmoid(x) + + +class GroupNorm32(nn.GroupNorm): + def forward(self, x): + # return super().forward(x.float()).type(x.dtype) + return super().forward(x).type(x.dtype) + +def conv_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D convolution module. + """ + if dims == 1: + return nn.Conv1d(*args, **kwargs) + elif dims == 2: + return nn.Conv2d(*args, **kwargs) + elif dims == 3: + return nn.Conv3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +def linear(*args, **kwargs): + """ + Create a linear module. + """ + return nn.Linear(*args, **kwargs) + + +def avg_pool_nd(dims, *args, **kwargs): + """ + Create a 1D, 2D, or 3D average pooling module. + """ + if dims == 1: + return nn.AvgPool1d(*args, **kwargs) + elif dims == 2: + return nn.AvgPool2d(*args, **kwargs) + elif dims == 3: + return nn.AvgPool3d(*args, **kwargs) + raise ValueError(f"unsupported dimensions: {dims}") + + +class HybridConditioner(nn.Module): + + def __init__(self, c_concat_config, c_crossattn_config): + super().__init__() + self.concat_conditioner = instantiate_from_config(c_concat_config) + self.crossattn_conditioner = instantiate_from_config(c_crossattn_config) + + def forward(self, c_concat, c_crossattn): + c_concat = self.concat_conditioner(c_concat) + c_crossattn = self.crossattn_conditioner(c_crossattn) + return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]} + + +def noise_like(shape, device, repeat=False): + repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1))) + noise = lambda: torch.randn(shape, device=device) + return repeat_noise() if repeat else noise() \ No newline at end of file diff --git a/py/iopaint/model/anytext/ldm/modules/distributions/__init__.py b/py/iopaint/model/anytext/ldm/modules/distributions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py b/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py new file mode 100644 index 0000000..f2b8ef9 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/distributions/distributions.py @@ -0,0 +1,92 @@ +import torch +import numpy as np + + +class AbstractDistribution: + def sample(self): + raise NotImplementedError() + + def mode(self): + raise NotImplementedError() + + +class DiracDistribution(AbstractDistribution): + def __init__(self, value): + self.value = value + + def sample(self): + return self.value + + def mode(self): + return self.value + + +class DiagonalGaussianDistribution(object): + def __init__(self, parameters, deterministic=False): + self.parameters = parameters + self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) + self.logvar = torch.clamp(self.logvar, -30.0, 20.0) + self.deterministic = deterministic + self.std = torch.exp(0.5 * self.logvar) + self.var = torch.exp(self.logvar) + if self.deterministic: + self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device) + + def sample(self): + x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device) + return x + + def kl(self, other=None): + if self.deterministic: + return torch.Tensor([0.]) + else: + if other is None: + return 0.5 * torch.sum(torch.pow(self.mean, 2) + + self.var - 1.0 - self.logvar, + dim=[1, 2, 3]) + else: + return 0.5 * torch.sum( + torch.pow(self.mean - other.mean, 2) / other.var + + self.var / other.var - 1.0 - self.logvar + other.logvar, + dim=[1, 2, 3]) + + def nll(self, sample, dims=[1,2,3]): + if self.deterministic: + return torch.Tensor([0.]) + logtwopi = np.log(2.0 * np.pi) + return 0.5 * torch.sum( + logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, + dim=dims) + + def mode(self): + return self.mean + + +def normal_kl(mean1, logvar1, mean2, logvar2): + """ + source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12 + Compute the KL divergence between two gaussians. + Shapes are automatically broadcasted, so batches can be compared to + scalars, among other use cases. + """ + tensor = None + for obj in (mean1, logvar1, mean2, logvar2): + if isinstance(obj, torch.Tensor): + tensor = obj + break + assert tensor is not None, "at least one argument must be a Tensor" + + # Force variances to be Tensors. Broadcasting helps convert scalars to + # Tensors, but it does not work for torch.exp(). + logvar1, logvar2 = [ + x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor) + for x in (logvar1, logvar2) + ] + + return 0.5 * ( + -1.0 + + logvar2 + - logvar1 + + torch.exp(logvar1 - logvar2) + + ((mean1 - mean2) ** 2) * torch.exp(-logvar2) + ) diff --git a/py/iopaint/model/anytext/ldm/modules/ema.py b/py/iopaint/model/anytext/ldm/modules/ema.py new file mode 100644 index 0000000..bded250 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/ema.py @@ -0,0 +1,80 @@ +import torch +from torch import nn + + +class LitEma(nn.Module): + def __init__(self, model, decay=0.9999, use_num_upates=True): + super().__init__() + if decay < 0.0 or decay > 1.0: + raise ValueError('Decay must be between 0 and 1') + + self.m_name2s_name = {} + self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32)) + self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int) if use_num_upates + else torch.tensor(-1, dtype=torch.int)) + + for name, p in model.named_parameters(): + if p.requires_grad: + # remove as '.'-character is not allowed in buffers + s_name = name.replace('.', '') + self.m_name2s_name.update({name: s_name}) + self.register_buffer(s_name, p.clone().detach().data) + + self.collected_params = [] + + def reset_num_updates(self): + del self.num_updates + self.register_buffer('num_updates', torch.tensor(0, dtype=torch.int)) + + def forward(self, model): + decay = self.decay + + if self.num_updates >= 0: + self.num_updates += 1 + decay = min(self.decay, (1 + self.num_updates) / (10 + self.num_updates)) + + one_minus_decay = 1.0 - decay + + with torch.no_grad(): + m_param = dict(model.named_parameters()) + shadow_params = dict(self.named_buffers()) + + for key in m_param: + if m_param[key].requires_grad: + sname = self.m_name2s_name[key] + shadow_params[sname] = shadow_params[sname].type_as(m_param[key]) + shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key])) + else: + assert not key in self.m_name2s_name + + def copy_to(self, model): + m_param = dict(model.named_parameters()) + shadow_params = dict(self.named_buffers()) + for key in m_param: + if m_param[key].requires_grad: + m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data) + else: + assert not key in self.m_name2s_name + + def store(self, parameters): + """ + Save the current parameters for restoring later. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + temporarily stored. + """ + self.collected_params = [param.clone() for param in parameters] + + def restore(self, parameters): + """ + Restore the parameters stored with the `store` method. + Useful to validate the model with EMA parameters without affecting the + original optimization process. Store the parameters before the + `copy_to` method. After validation (or model saving), use this to + restore the former parameters. + Args: + parameters: Iterable of `torch.nn.Parameter`; the parameters to be + updated with the stored parameters. + """ + for c_param, param in zip(self.collected_params, parameters): + param.data.copy_(c_param.data) diff --git a/py/iopaint/model/anytext/ldm/modules/encoders/__init__.py b/py/iopaint/model/anytext/ldm/modules/encoders/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ldm/modules/encoders/modules.py b/py/iopaint/model/anytext/ldm/modules/encoders/modules.py new file mode 100644 index 0000000..ceac395 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/modules/encoders/modules.py @@ -0,0 +1,411 @@ +import torch +import torch.nn as nn +from torch.utils.checkpoint import checkpoint + +from transformers import ( + T5Tokenizer, + T5EncoderModel, + CLIPTokenizer, + CLIPTextModel, + AutoProcessor, + CLIPVisionModelWithProjection, +) + +from iopaint.model.anytext.ldm.util import count_params + + +def _expand_mask(mask, dtype, tgt_len=None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill( + inverted_mask.to(torch.bool), torch.finfo(dtype).min + ) + + +def _build_causal_attention_mask(bsz, seq_len, dtype): + # lazily create causal attention mask, with full attention between the vision tokens + # pytorch uses additive attention mask; fill with -inf + mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype) + mask.fill_(torch.tensor(torch.finfo(dtype).min)) + mask.triu_(1) # zero out the lower diagonal + mask = mask.unsqueeze(1) # expand mask + return mask + + +class AbstractEncoder(nn.Module): + def __init__(self): + super().__init__() + + def encode(self, *args, **kwargs): + raise NotImplementedError + + +class IdentityEncoder(AbstractEncoder): + def encode(self, x): + return x + + +class ClassEmbedder(nn.Module): + def __init__(self, embed_dim, n_classes=1000, key="class", ucg_rate=0.1): + super().__init__() + self.key = key + self.embedding = nn.Embedding(n_classes, embed_dim) + self.n_classes = n_classes + self.ucg_rate = ucg_rate + + def forward(self, batch, key=None, disable_dropout=False): + if key is None: + key = self.key + # this is for use in crossattn + c = batch[key][:, None] + if self.ucg_rate > 0.0 and not disable_dropout: + mask = 1.0 - torch.bernoulli(torch.ones_like(c) * self.ucg_rate) + c = mask * c + (1 - mask) * torch.ones_like(c) * (self.n_classes - 1) + c = c.long() + c = self.embedding(c) + return c + + def get_unconditional_conditioning(self, bs, device="cuda"): + uc_class = ( + self.n_classes - 1 + ) # 1000 classes --> 0 ... 999, one extra class for ucg (class 1000) + uc = torch.ones((bs,), device=device) * uc_class + uc = {self.key: uc} + return uc + + +def disabled_train(self, mode=True): + """Overwrite model.train with this function to make sure train/eval mode + does not change anymore.""" + return self + + +class FrozenT5Embedder(AbstractEncoder): + """Uses the T5 transformer encoder for text""" + + def __init__( + self, version="google/t5-v1_1-large", device="cuda", max_length=77, freeze=True + ): # others are google/t5-v1_1-xl and google/t5-v1_1-xxl + super().__init__() + self.tokenizer = T5Tokenizer.from_pretrained(version) + self.transformer = T5EncoderModel.from_pretrained(version) + self.device = device + self.max_length = max_length # TODO: typical value? + if freeze: + self.freeze() + + def freeze(self): + self.transformer = self.transformer.eval() + # self.train = disabled_train + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + outputs = self.transformer(input_ids=tokens) + + z = outputs.last_hidden_state + return z + + def encode(self, text): + return self(text) + + +class FrozenCLIPEmbedder(AbstractEncoder): + """Uses the CLIP transformer encoder for text (from huggingface)""" + + LAYERS = ["last", "pooled", "hidden"] + + def __init__( + self, + version="openai/clip-vit-large-patch14", + device="cuda", + max_length=77, + freeze=True, + layer="last", + layer_idx=None, + ): # clip-vit-base-patch32 + super().__init__() + assert layer in self.LAYERS + self.tokenizer = CLIPTokenizer.from_pretrained(version) + self.transformer = CLIPTextModel.from_pretrained(version) + self.device = device + self.max_length = max_length + if freeze: + self.freeze() + self.layer = layer + self.layer_idx = layer_idx + if layer == "hidden": + assert layer_idx is not None + assert 0 <= abs(layer_idx) <= 12 + + def freeze(self): + self.transformer = self.transformer.eval() + # self.train = disabled_train + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + outputs = self.transformer( + input_ids=tokens, output_hidden_states=self.layer == "hidden" + ) + if self.layer == "last": + z = outputs.last_hidden_state + elif self.layer == "pooled": + z = outputs.pooler_output[:, None, :] + else: + z = outputs.hidden_states[self.layer_idx] + return z + + def encode(self, text): + return self(text) + + +class FrozenCLIPT5Encoder(AbstractEncoder): + def __init__( + self, + clip_version="openai/clip-vit-large-patch14", + t5_version="google/t5-v1_1-xl", + device="cuda", + clip_max_length=77, + t5_max_length=77, + ): + super().__init__() + self.clip_encoder = FrozenCLIPEmbedder( + clip_version, device, max_length=clip_max_length + ) + self.t5_encoder = FrozenT5Embedder(t5_version, device, max_length=t5_max_length) + print( + f"{self.clip_encoder.__class__.__name__} has {count_params(self.clip_encoder)*1.e-6:.2f} M parameters, " + f"{self.t5_encoder.__class__.__name__} comes with {count_params(self.t5_encoder)*1.e-6:.2f} M params." + ) + + def encode(self, text): + return self(text) + + def forward(self, text): + clip_z = self.clip_encoder.encode(text) + t5_z = self.t5_encoder.encode(text) + return [clip_z, t5_z] + + +class FrozenCLIPEmbedderT3(AbstractEncoder): + """Uses the CLIP transformer encoder for text (from Hugging Face)""" + + def __init__( + self, + version="openai/clip-vit-large-patch14", + device="cuda", + max_length=77, + freeze=True, + use_vision=False, + ): + super().__init__() + self.tokenizer = CLIPTokenizer.from_pretrained(version) + self.transformer = CLIPTextModel.from_pretrained(version) + if use_vision: + self.vit = CLIPVisionModelWithProjection.from_pretrained(version) + self.processor = AutoProcessor.from_pretrained(version) + self.device = device + self.max_length = max_length + if freeze: + self.freeze() + + def embedding_forward( + self, + input_ids=None, + position_ids=None, + inputs_embeds=None, + embedding_manager=None, + ): + seq_length = ( + input_ids.shape[-1] + if input_ids is not None + else inputs_embeds.shape[-2] + ) + if position_ids is None: + position_ids = self.position_ids[:, :seq_length] + if inputs_embeds is None: + inputs_embeds = self.token_embedding(input_ids) + if embedding_manager is not None: + inputs_embeds = embedding_manager(input_ids, inputs_embeds) + position_embeddings = self.position_embedding(position_ids) + embeddings = inputs_embeds + position_embeddings + return embeddings + + self.transformer.text_model.embeddings.forward = embedding_forward.__get__( + self.transformer.text_model.embeddings + ) + + def encoder_forward( + self, + inputs_embeds, + attention_mask=None, + causal_attention_mask=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + ): + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + encoder_states = () if output_hidden_states else None + all_attentions = () if output_attentions else None + hidden_states = inputs_embeds + for idx, encoder_layer in enumerate(self.layers): + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + layer_outputs = encoder_layer( + hidden_states, + attention_mask, + causal_attention_mask, + output_attentions=output_attentions, + ) + hidden_states = layer_outputs[0] + if output_attentions: + all_attentions = all_attentions + (layer_outputs[1],) + if output_hidden_states: + encoder_states = encoder_states + (hidden_states,) + return hidden_states + + self.transformer.text_model.encoder.forward = encoder_forward.__get__( + self.transformer.text_model.encoder + ) + + def text_encoder_forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + embedding_manager=None, + ): + output_attentions = ( + output_attentions + if output_attentions is not None + else self.config.output_attentions + ) + output_hidden_states = ( + output_hidden_states + if output_hidden_states is not None + else self.config.output_hidden_states + ) + return_dict = ( + return_dict if return_dict is not None else self.config.use_return_dict + ) + if input_ids is None: + raise ValueError("You have to specify either input_ids") + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + hidden_states = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + embedding_manager=embedding_manager, + ) + bsz, seq_len = input_shape + # CLIP's text model uses causal mask, prepare it here. + # https://github.com/openai/CLIP/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clip/model.py#L324 + causal_attention_mask = _build_causal_attention_mask( + bsz, seq_len, hidden_states.dtype + ).to(hidden_states.device) + # expand attention_mask + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + attention_mask = _expand_mask(attention_mask, hidden_states.dtype) + last_hidden_state = self.encoder( + inputs_embeds=hidden_states, + attention_mask=attention_mask, + causal_attention_mask=causal_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + last_hidden_state = self.final_layer_norm(last_hidden_state) + return last_hidden_state + + self.transformer.text_model.forward = text_encoder_forward.__get__( + self.transformer.text_model + ) + + def transformer_forward( + self, + input_ids=None, + attention_mask=None, + position_ids=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + embedding_manager=None, + ): + return self.text_model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + embedding_manager=embedding_manager, + ) + + self.transformer.forward = transformer_forward.__get__(self.transformer) + + def freeze(self): + self.transformer = self.transformer.eval() + for param in self.parameters(): + param.requires_grad = False + + def forward(self, text, **kwargs): + batch_encoding = self.tokenizer( + text, + truncation=True, + max_length=self.max_length, + return_length=True, + return_overflowing_tokens=False, + padding="max_length", + return_tensors="pt", + ) + tokens = batch_encoding["input_ids"].to(self.device) + z = self.transformer(input_ids=tokens, **kwargs) + return z + + def encode(self, text, **kwargs): + return self(text, **kwargs) diff --git a/py/iopaint/model/anytext/ldm/util.py b/py/iopaint/model/anytext/ldm/util.py new file mode 100644 index 0000000..d456a86 --- /dev/null +++ b/py/iopaint/model/anytext/ldm/util.py @@ -0,0 +1,197 @@ +import importlib + +import torch +from torch import optim +import numpy as np + +from inspect import isfunction +from PIL import Image, ImageDraw, ImageFont + + +def log_txt_as_img(wh, xc, size=10): + # wh a tuple of (width, height) + # xc a list of captions to plot + b = len(xc) + txts = list() + for bi in range(b): + txt = Image.new("RGB", wh, color="white") + draw = ImageDraw.Draw(txt) + font = ImageFont.truetype('font/Arial_Unicode.ttf', size=size) + nc = int(32 * (wh[0] / 256)) + lines = "\n".join(xc[bi][start:start + nc] for start in range(0, len(xc[bi]), nc)) + + try: + draw.text((0, 0), lines, fill="black", font=font) + except UnicodeEncodeError: + print("Cant encode string for logging. Skipping.") + + txt = np.array(txt).transpose(2, 0, 1) / 127.5 - 1.0 + txts.append(txt) + txts = np.stack(txts) + txts = torch.tensor(txts) + return txts + + +def ismap(x): + if not isinstance(x, torch.Tensor): + return False + return (len(x.shape) == 4) and (x.shape[1] > 3) + + +def isimage(x): + if not isinstance(x,torch.Tensor): + return False + return (len(x.shape) == 4) and (x.shape[1] == 3 or x.shape[1] == 1) + + +def exists(x): + return x is not None + + +def default(val, d): + if exists(val): + return val + return d() if isfunction(d) else d + + +def mean_flat(tensor): + """ + https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 + Take the mean over all non-batch dimensions. + """ + return tensor.mean(dim=list(range(1, len(tensor.shape)))) + + +def count_params(model, verbose=False): + total_params = sum(p.numel() for p in model.parameters()) + if verbose: + print(f"{model.__class__.__name__} has {total_params*1.e-6:.2f} M params.") + return total_params + + +def instantiate_from_config(config, **kwargs): + if "target" not in config: + if config == '__is_first_stage__': + return None + elif config == "__is_unconditional__": + return None + raise KeyError("Expected key `target` to instantiate.") + return get_obj_from_str(config["target"])(**config.get("params", dict()), **kwargs) + + +def get_obj_from_str(string, reload=False): + module, cls = string.rsplit(".", 1) + if reload: + module_imp = importlib.import_module(module) + importlib.reload(module_imp) + return getattr(importlib.import_module(module, package=None), cls) + + +class AdamWwithEMAandWings(optim.Optimizer): + # credit to https://gist.github.com/crowsonkb/65f7265353f403714fce3b2595e0b298 + def __init__(self, params, lr=1.e-3, betas=(0.9, 0.999), eps=1.e-8, # TODO: check hyperparameters before using + weight_decay=1.e-2, amsgrad=False, ema_decay=0.9999, # ema decay to match previous code + ema_power=1., param_names=()): + """AdamW that saves EMA versions of the parameters.""" + if not 0.0 <= lr: + raise ValueError("Invalid learning rate: {}".format(lr)) + if not 0.0 <= eps: + raise ValueError("Invalid epsilon value: {}".format(eps)) + if not 0.0 <= betas[0] < 1.0: + raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) + if not 0.0 <= betas[1] < 1.0: + raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) + if not 0.0 <= weight_decay: + raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) + if not 0.0 <= ema_decay <= 1.0: + raise ValueError("Invalid ema_decay value: {}".format(ema_decay)) + defaults = dict(lr=lr, betas=betas, eps=eps, + weight_decay=weight_decay, amsgrad=amsgrad, ema_decay=ema_decay, + ema_power=ema_power, param_names=param_names) + super().__init__(params, defaults) + + def __setstate__(self, state): + super().__setstate__(state) + for group in self.param_groups: + group.setdefault('amsgrad', False) + + @torch.no_grad() + def step(self, closure=None): + """Performs a single optimization step. + Args: + closure (callable, optional): A closure that reevaluates the model + and returns the loss. + """ + loss = None + if closure is not None: + with torch.enable_grad(): + loss = closure() + + for group in self.param_groups: + params_with_grad = [] + grads = [] + exp_avgs = [] + exp_avg_sqs = [] + ema_params_with_grad = [] + state_sums = [] + max_exp_avg_sqs = [] + state_steps = [] + amsgrad = group['amsgrad'] + beta1, beta2 = group['betas'] + ema_decay = group['ema_decay'] + ema_power = group['ema_power'] + + for p in group['params']: + if p.grad is None: + continue + params_with_grad.append(p) + if p.grad.is_sparse: + raise RuntimeError('AdamW does not support sparse gradients') + grads.append(p.grad) + + state = self.state[p] + + # State initialization + if len(state) == 0: + state['step'] = 0 + # Exponential moving average of gradient values + state['exp_avg'] = torch.zeros_like(p, memory_format=torch.preserve_format) + # Exponential moving average of squared gradient values + state['exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) + if amsgrad: + # Maintains max of all exp. moving avg. of sq. grad. values + state['max_exp_avg_sq'] = torch.zeros_like(p, memory_format=torch.preserve_format) + # Exponential moving average of parameter values + state['param_exp_avg'] = p.detach().float().clone() + + exp_avgs.append(state['exp_avg']) + exp_avg_sqs.append(state['exp_avg_sq']) + ema_params_with_grad.append(state['param_exp_avg']) + + if amsgrad: + max_exp_avg_sqs.append(state['max_exp_avg_sq']) + + # update the steps for each param group update + state['step'] += 1 + # record the step after step update + state_steps.append(state['step']) + + optim._functional.adamw(params_with_grad, + grads, + exp_avgs, + exp_avg_sqs, + max_exp_avg_sqs, + state_steps, + amsgrad=amsgrad, + beta1=beta1, + beta2=beta2, + lr=group['lr'], + weight_decay=group['weight_decay'], + eps=group['eps'], + maximize=False) + + cur_ema_decay = min(ema_decay, 1 - state['step'] ** -ema_power) + for param, ema_param in zip(params_with_grad, ema_params_with_grad): + ema_param.mul_(cur_ema_decay).add_(param.float(), alpha=1 - cur_ema_decay) + + return loss \ No newline at end of file diff --git a/py/iopaint/model/anytext/main.py b/py/iopaint/model/anytext/main.py new file mode 100644 index 0000000..f7b2d2e --- /dev/null +++ b/py/iopaint/model/anytext/main.py @@ -0,0 +1,45 @@ +import cv2 +import os + +from anytext_pipeline import AnyTextPipeline +from utils import save_images + +seed = 66273235 +# seed_everything(seed) + +pipe = AnyTextPipeline( + ckpt_path="/Users/cwq/code/github/IOPaint/iopaint/model/anytext/anytext_v1.1_fp16.ckpt", + font_path="/Users/cwq/code/github/AnyText/anytext/font/SourceHanSansSC-Medium.otf", + use_fp16=False, + device="mps", +) + +img_save_folder = "SaveImages" +rgb_image = cv2.imread( + "/Users/cwq/code/github/AnyText/anytext/example_images/ref7.jpg" +)[..., ::-1] + +masked_image = cv2.imread( + "/Users/cwq/code/github/AnyText/anytext/example_images/edit7.png" +)[..., ::-1] + +rgb_image = cv2.resize(rgb_image, (512, 512)) +masked_image = cv2.resize(masked_image, (512, 512)) + +# results: list of rgb ndarray +results, rtn_code, rtn_warning = pipe( + prompt='A cake with colorful characters that reads "EVERYDAY", best quality, extremely detailed,4k, HD, supper legible text, clear text edges, clear strokes, neat writing, no watermarks', + negative_prompt="low-res, bad anatomy, extra digit, fewer digits, cropped, worst quality, low quality, watermark, unreadable text, messy words, distorted text, disorganized writing, advertising picture", + image=rgb_image, + masked_image=masked_image, + num_inference_steps=20, + strength=1.0, + guidance_scale=9.0, + height=rgb_image.shape[0], + width=rgb_image.shape[1], + seed=seed, + sort_priority="y", +) +if rtn_code >= 0: + save_images(results, img_save_folder) + print(f"Done, result images are saved in: {img_save_folder}") diff --git a/py/iopaint/model/anytext/ocr_recog/RNN.py b/py/iopaint/model/anytext/ocr_recog/RNN.py new file mode 100644 index 0000000..cf16855 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RNN.py @@ -0,0 +1,210 @@ +from torch import nn +import torch +from .RecSVTR import Block + +class Swish(nn.Module): + def __int__(self): + super(Swish, self).__int__() + + def forward(self,x): + return x*torch.sigmoid(x) + +class Im2Im(nn.Module): + def __init__(self, in_channels, **kwargs): + super().__init__() + self.out_channels = in_channels + + def forward(self, x): + return x + +class Im2Seq(nn.Module): + def __init__(self, in_channels, **kwargs): + super().__init__() + self.out_channels = in_channels + + def forward(self, x): + B, C, H, W = x.shape + # assert H == 1 + x = x.reshape(B, C, H * W) + x = x.permute((0, 2, 1)) + return x + +class EncoderWithRNN(nn.Module): + def __init__(self, in_channels,**kwargs): + super(EncoderWithRNN, self).__init__() + hidden_size = kwargs.get('hidden_size', 256) + self.out_channels = hidden_size * 2 + self.lstm = nn.LSTM(in_channels, hidden_size, bidirectional=True, num_layers=2,batch_first=True) + + def forward(self, x): + self.lstm.flatten_parameters() + x, _ = self.lstm(x) + return x + +class SequenceEncoder(nn.Module): + def __init__(self, in_channels, encoder_type='rnn', **kwargs): + super(SequenceEncoder, self).__init__() + self.encoder_reshape = Im2Seq(in_channels) + self.out_channels = self.encoder_reshape.out_channels + self.encoder_type = encoder_type + if encoder_type == 'reshape': + self.only_reshape = True + else: + support_encoder_dict = { + 'reshape': Im2Seq, + 'rnn': EncoderWithRNN, + 'svtr': EncoderWithSVTR + } + assert encoder_type in support_encoder_dict, '{} must in {}'.format( + encoder_type, support_encoder_dict.keys()) + + self.encoder = support_encoder_dict[encoder_type]( + self.encoder_reshape.out_channels,**kwargs) + self.out_channels = self.encoder.out_channels + self.only_reshape = False + + def forward(self, x): + if self.encoder_type != 'svtr': + x = self.encoder_reshape(x) + if not self.only_reshape: + x = self.encoder(x) + return x + else: + x = self.encoder(x) + x = self.encoder_reshape(x) + return x + +class ConvBNLayer(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=0, + bias_attr=False, + groups=1, + act=nn.GELU): + super().__init__() + self.conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + # weight_attr=paddle.ParamAttr(initializer=nn.initializer.KaimingUniform()), + bias=bias_attr) + self.norm = nn.BatchNorm2d(out_channels) + self.act = Swish() + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + out = self.act(out) + return out + + +class EncoderWithSVTR(nn.Module): + def __init__( + self, + in_channels, + dims=64, # XS + depth=2, + hidden_dims=120, + use_guide=False, + num_heads=8, + qkv_bias=True, + mlp_ratio=2.0, + drop_rate=0.1, + attn_drop_rate=0.1, + drop_path=0., + qk_scale=None): + super(EncoderWithSVTR, self).__init__() + self.depth = depth + self.use_guide = use_guide + self.conv1 = ConvBNLayer( + in_channels, in_channels // 8, padding=1, act='swish') + self.conv2 = ConvBNLayer( + in_channels // 8, hidden_dims, kernel_size=1, act='swish') + + self.svtr_block = nn.ModuleList([ + Block( + dim=hidden_dims, + num_heads=num_heads, + mixer='Global', + HW=None, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer='swish', + attn_drop=attn_drop_rate, + drop_path=drop_path, + norm_layer='nn.LayerNorm', + epsilon=1e-05, + prenorm=False) for i in range(depth) + ]) + self.norm = nn.LayerNorm(hidden_dims, eps=1e-6) + self.conv3 = ConvBNLayer( + hidden_dims, in_channels, kernel_size=1, act='swish') + # last conv-nxn, the input is concat of input tensor and conv3 output tensor + self.conv4 = ConvBNLayer( + 2 * in_channels, in_channels // 8, padding=1, act='swish') + + self.conv1x1 = ConvBNLayer( + in_channels // 8, dims, kernel_size=1, act='swish') + self.out_channels = dims + self.apply(self._init_weights) + + def _init_weights(self, m): + # weight initialization + if isinstance(m, nn.Conv2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.BatchNorm2d): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + elif isinstance(m, nn.Linear): + nn.init.normal_(m.weight, 0, 0.01) + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.ConvTranspose2d): + nn.init.kaiming_normal_(m.weight, mode='fan_out') + if m.bias is not None: + nn.init.zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + nn.init.ones_(m.weight) + nn.init.zeros_(m.bias) + + def forward(self, x): + # for use guide + if self.use_guide: + z = x.clone() + z.stop_gradient = True + else: + z = x + # for short cut + h = z + # reduce dim + z = self.conv1(z) + z = self.conv2(z) + # SVTR global block + B, C, H, W = z.shape + z = z.flatten(2).permute(0, 2, 1) + + for blk in self.svtr_block: + z = blk(z) + + z = self.norm(z) + # last stage + z = z.reshape([-1, H, W, C]).permute(0, 3, 1, 2) + z = self.conv3(z) + z = torch.cat((h, z), dim=1) + z = self.conv1x1(self.conv4(z)) + + return z + +if __name__=="__main__": + svtrRNN = EncoderWithSVTR(56) + print(svtrRNN) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py b/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py new file mode 100644 index 0000000..867ede9 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecCTCHead.py @@ -0,0 +1,48 @@ +from torch import nn + + +class CTCHead(nn.Module): + def __init__(self, + in_channels, + out_channels=6625, + fc_decay=0.0004, + mid_channels=None, + return_feats=False, + **kwargs): + super(CTCHead, self).__init__() + if mid_channels is None: + self.fc = nn.Linear( + in_channels, + out_channels, + bias=True,) + else: + self.fc1 = nn.Linear( + in_channels, + mid_channels, + bias=True, + ) + self.fc2 = nn.Linear( + mid_channels, + out_channels, + bias=True, + ) + + self.out_channels = out_channels + self.mid_channels = mid_channels + self.return_feats = return_feats + + def forward(self, x, labels=None): + if self.mid_channels is None: + predicts = self.fc(x) + else: + x = self.fc1(x) + predicts = self.fc2(x) + + if self.return_feats: + result = dict() + result['ctc'] = predicts + result['ctc_neck'] = x + else: + result = predicts + + return result diff --git a/py/iopaint/model/anytext/ocr_recog/RecModel.py b/py/iopaint/model/anytext/ocr_recog/RecModel.py new file mode 100644 index 0000000..c2313bf --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecModel.py @@ -0,0 +1,45 @@ +from torch import nn +from .RNN import SequenceEncoder, Im2Seq, Im2Im +from .RecMv1_enhance import MobileNetV1Enhance + +from .RecCTCHead import CTCHead + +backbone_dict = {"MobileNetV1Enhance":MobileNetV1Enhance} +neck_dict = {'SequenceEncoder': SequenceEncoder, 'Im2Seq': Im2Seq,'None':Im2Im} +head_dict = {'CTCHead':CTCHead} + + +class RecModel(nn.Module): + def __init__(self, config): + super().__init__() + assert 'in_channels' in config, 'in_channels must in model config' + backbone_type = config.backbone.pop('type') + assert backbone_type in backbone_dict, f'backbone.type must in {backbone_dict}' + self.backbone = backbone_dict[backbone_type](config.in_channels, **config.backbone) + + neck_type = config.neck.pop('type') + assert neck_type in neck_dict, f'neck.type must in {neck_dict}' + self.neck = neck_dict[neck_type](self.backbone.out_channels, **config.neck) + + head_type = config.head.pop('type') + assert head_type in head_dict, f'head.type must in {head_dict}' + self.head = head_dict[head_type](self.neck.out_channels, **config.head) + + self.name = f'RecModel_{backbone_type}_{neck_type}_{head_type}' + + def load_3rd_state_dict(self, _3rd_name, _state): + self.backbone.load_3rd_state_dict(_3rd_name, _state) + self.neck.load_3rd_state_dict(_3rd_name, _state) + self.head.load_3rd_state_dict(_3rd_name, _state) + + def forward(self, x): + x = self.backbone(x) + x = self.neck(x) + x = self.head(x) + return x + + def encode(self, x): + x = self.backbone(x) + x = self.neck(x) + x = self.head.ctc_encoder(x) + return x diff --git a/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py b/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py new file mode 100644 index 0000000..7529b4a --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecMv1_enhance.py @@ -0,0 +1,232 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +from .common import Activation + + +class ConvBNLayer(nn.Module): + def __init__(self, + num_channels, + filter_size, + num_filters, + stride, + padding, + channels=None, + num_groups=1, + act='hard_swish'): + super(ConvBNLayer, self).__init__() + self.act = act + self._conv = nn.Conv2d( + in_channels=num_channels, + out_channels=num_filters, + kernel_size=filter_size, + stride=stride, + padding=padding, + groups=num_groups, + bias=False) + + self._batch_norm = nn.BatchNorm2d( + num_filters, + ) + if self.act is not None: + self._act = Activation(act_type=act, inplace=True) + + def forward(self, inputs): + y = self._conv(inputs) + y = self._batch_norm(y) + if self.act is not None: + y = self._act(y) + return y + + +class DepthwiseSeparable(nn.Module): + def __init__(self, + num_channels, + num_filters1, + num_filters2, + num_groups, + stride, + scale, + dw_size=3, + padding=1, + use_se=False): + super(DepthwiseSeparable, self).__init__() + self.use_se = use_se + self._depthwise_conv = ConvBNLayer( + num_channels=num_channels, + num_filters=int(num_filters1 * scale), + filter_size=dw_size, + stride=stride, + padding=padding, + num_groups=int(num_groups * scale)) + if use_se: + self._se = SEModule(int(num_filters1 * scale)) + self._pointwise_conv = ConvBNLayer( + num_channels=int(num_filters1 * scale), + filter_size=1, + num_filters=int(num_filters2 * scale), + stride=1, + padding=0) + + def forward(self, inputs): + y = self._depthwise_conv(inputs) + if self.use_se: + y = self._se(y) + y = self._pointwise_conv(y) + return y + + +class MobileNetV1Enhance(nn.Module): + def __init__(self, + in_channels=3, + scale=0.5, + last_conv_stride=1, + last_pool_type='max', + **kwargs): + super().__init__() + self.scale = scale + self.block_list = [] + + self.conv1 = ConvBNLayer( + num_channels=in_channels, + filter_size=3, + channels=3, + num_filters=int(32 * scale), + stride=2, + padding=1) + + conv2_1 = DepthwiseSeparable( + num_channels=int(32 * scale), + num_filters1=32, + num_filters2=64, + num_groups=32, + stride=1, + scale=scale) + self.block_list.append(conv2_1) + + conv2_2 = DepthwiseSeparable( + num_channels=int(64 * scale), + num_filters1=64, + num_filters2=128, + num_groups=64, + stride=1, + scale=scale) + self.block_list.append(conv2_2) + + conv3_1 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=128, + num_groups=128, + stride=1, + scale=scale) + self.block_list.append(conv3_1) + + conv3_2 = DepthwiseSeparable( + num_channels=int(128 * scale), + num_filters1=128, + num_filters2=256, + num_groups=128, + stride=(2, 1), + scale=scale) + self.block_list.append(conv3_2) + + conv4_1 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=256, + num_groups=256, + stride=1, + scale=scale) + self.block_list.append(conv4_1) + + conv4_2 = DepthwiseSeparable( + num_channels=int(256 * scale), + num_filters1=256, + num_filters2=512, + num_groups=256, + stride=(2, 1), + scale=scale) + self.block_list.append(conv4_2) + + for _ in range(5): + conv5 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=512, + num_groups=512, + stride=1, + dw_size=5, + padding=2, + scale=scale, + use_se=False) + self.block_list.append(conv5) + + conv5_6 = DepthwiseSeparable( + num_channels=int(512 * scale), + num_filters1=512, + num_filters2=1024, + num_groups=512, + stride=(2, 1), + dw_size=5, + padding=2, + scale=scale, + use_se=True) + self.block_list.append(conv5_6) + + conv6 = DepthwiseSeparable( + num_channels=int(1024 * scale), + num_filters1=1024, + num_filters2=1024, + num_groups=1024, + stride=last_conv_stride, + dw_size=5, + padding=2, + use_se=True, + scale=scale) + self.block_list.append(conv6) + + self.block_list = nn.Sequential(*self.block_list) + if last_pool_type == 'avg': + self.pool = nn.AvgPool2d(kernel_size=2, stride=2, padding=0) + else: + self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) + self.out_channels = int(1024 * scale) + + def forward(self, inputs): + y = self.conv1(inputs) + y = self.block_list(y) + y = self.pool(y) + return y + +def hardsigmoid(x): + return F.relu6(x + 3., inplace=True) / 6. + +class SEModule(nn.Module): + def __init__(self, channel, reduction=4): + super(SEModule, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.conv1 = nn.Conv2d( + in_channels=channel, + out_channels=channel // reduction, + kernel_size=1, + stride=1, + padding=0, + bias=True) + self.conv2 = nn.Conv2d( + in_channels=channel // reduction, + out_channels=channel, + kernel_size=1, + stride=1, + padding=0, + bias=True) + + def forward(self, inputs): + outputs = self.avg_pool(inputs) + outputs = self.conv1(outputs) + outputs = F.relu(outputs) + outputs = self.conv2(outputs) + outputs = hardsigmoid(outputs) + x = torch.mul(inputs, outputs) + + return x diff --git a/py/iopaint/model/anytext/ocr_recog/RecSVTR.py b/py/iopaint/model/anytext/ocr_recog/RecSVTR.py new file mode 100644 index 0000000..484b3df --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/RecSVTR.py @@ -0,0 +1,591 @@ +import torch +import torch.nn as nn +import numpy as np +from torch.nn.init import trunc_normal_, zeros_, ones_ +from torch.nn import functional + + +def drop_path(x, drop_prob=0., training=False): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... + """ + if drop_prob == 0. or not training: + return x + keep_prob = torch.tensor(1 - drop_prob) + shape = (x.size()[0], ) + (1, ) * (x.ndim - 1) + random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype) + random_tensor = torch.floor(random_tensor) # binarize + output = x.divide(keep_prob) * random_tensor + return output + + +class Swish(nn.Module): + def __int__(self): + super(Swish, self).__int__() + + def forward(self,x): + return x*torch.sigmoid(x) + + +class ConvBNLayer(nn.Module): + def __init__(self, + in_channels, + out_channels, + kernel_size=3, + stride=1, + padding=0, + bias_attr=False, + groups=1, + act=nn.GELU): + super().__init__() + self.conv = nn.Conv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=stride, + padding=padding, + groups=groups, + # weight_attr=paddle.ParamAttr(initializer=nn.initializer.KaimingUniform()), + bias=bias_attr) + self.norm = nn.BatchNorm2d(out_channels) + self.act = act() + + def forward(self, inputs): + out = self.conv(inputs) + out = self.norm(out) + out = self.act(out) + return out + + +class DropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + """ + + def __init__(self, drop_prob=None): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training) + + +class Identity(nn.Module): + def __init__(self): + super(Identity, self).__init__() + + def forward(self, input): + return input + + +class Mlp(nn.Module): + def __init__(self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = nn.Linear(in_features, hidden_features) + if isinstance(act_layer, str): + self.act = Swish() + else: + self.act = act_layer() + self.fc2 = nn.Linear(hidden_features, out_features) + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class ConvMixer(nn.Module): + def __init__( + self, + dim, + num_heads=8, + HW=(8, 25), + local_k=(3, 3), ): + super().__init__() + self.HW = HW + self.dim = dim + self.local_mixer = nn.Conv2d( + dim, + dim, + local_k, + 1, (local_k[0] // 2, local_k[1] // 2), + groups=num_heads, + # weight_attr=ParamAttr(initializer=KaimingNormal()) + ) + + def forward(self, x): + h = self.HW[0] + w = self.HW[1] + x = x.transpose([0, 2, 1]).reshape([0, self.dim, h, w]) + x = self.local_mixer(x) + x = x.flatten(2).transpose([0, 2, 1]) + return x + + +class Attention(nn.Module): + def __init__(self, + dim, + num_heads=8, + mixer='Global', + HW=(8, 25), + local_k=(7, 11), + qkv_bias=False, + qk_scale=None, + attn_drop=0., + proj_drop=0.): + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.attn_drop = nn.Dropout(attn_drop) + self.proj = nn.Linear(dim, dim) + self.proj_drop = nn.Dropout(proj_drop) + self.HW = HW + if HW is not None: + H = HW[0] + W = HW[1] + self.N = H * W + self.C = dim + if mixer == 'Local' and HW is not None: + hk = local_k[0] + wk = local_k[1] + mask = torch.ones([H * W, H + hk - 1, W + wk - 1]) + for h in range(0, H): + for w in range(0, W): + mask[h * W + w, h:h + hk, w:w + wk] = 0. + mask_paddle = mask[:, hk // 2:H + hk // 2, wk // 2:W + wk // + 2].flatten(1) + mask_inf = torch.full([H * W, H * W],fill_value=float('-inf')) + mask = torch.where(mask_paddle < 1, mask_paddle, mask_inf) + self.mask = mask[None,None,:] + # self.mask = mask.unsqueeze([0, 1]) + self.mixer = mixer + + def forward(self, x): + if self.HW is not None: + N = self.N + C = self.C + else: + _, N, C = x.shape + qkv = self.qkv(x).reshape((-1, N, 3, self.num_heads, C //self.num_heads)).permute((2, 0, 3, 1, 4)) + q, k, v = qkv[0] * self.scale, qkv[1], qkv[2] + + attn = (q.matmul(k.permute((0, 1, 3, 2)))) + if self.mixer == 'Local': + attn += self.mask + attn = functional.softmax(attn, dim=-1) + attn = self.attn_drop(attn) + + x = (attn.matmul(v)).permute((0, 2, 1, 3)).reshape((-1, N, C)) + x = self.proj(x) + x = self.proj_drop(x) + return x + + +class Block(nn.Module): + def __init__(self, + dim, + num_heads, + mixer='Global', + local_mixer=(7, 11), + HW=(8, 25), + mlp_ratio=4., + qkv_bias=False, + qk_scale=None, + drop=0., + attn_drop=0., + drop_path=0., + act_layer=nn.GELU, + norm_layer='nn.LayerNorm', + epsilon=1e-6, + prenorm=True): + super().__init__() + if isinstance(norm_layer, str): + self.norm1 = eval(norm_layer)(dim, eps=epsilon) + else: + self.norm1 = norm_layer(dim) + if mixer == 'Global' or mixer == 'Local': + + self.mixer = Attention( + dim, + num_heads=num_heads, + mixer=mixer, + HW=HW, + local_k=local_mixer, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop) + elif mixer == 'Conv': + self.mixer = ConvMixer( + dim, num_heads=num_heads, HW=HW, local_k=local_mixer) + else: + raise TypeError("The mixer must be one of [Global, Local, Conv]") + + self.drop_path = DropPath(drop_path) if drop_path > 0. else Identity() + if isinstance(norm_layer, str): + self.norm2 = eval(norm_layer)(dim, eps=epsilon) + else: + self.norm2 = norm_layer(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp_ratio = mlp_ratio + self.mlp = Mlp(in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop) + self.prenorm = prenorm + + def forward(self, x): + if self.prenorm: + x = self.norm1(x + self.drop_path(self.mixer(x))) + x = self.norm2(x + self.drop_path(self.mlp(x))) + else: + x = x + self.drop_path(self.mixer(self.norm1(x))) + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class PatchEmbed(nn.Module): + """ Image to Patch Embedding + """ + + def __init__(self, + img_size=(32, 100), + in_channels=3, + embed_dim=768, + sub_num=2): + super().__init__() + num_patches = (img_size[1] // (2 ** sub_num)) * \ + (img_size[0] // (2 ** sub_num)) + self.img_size = img_size + self.num_patches = num_patches + self.embed_dim = embed_dim + self.norm = None + if sub_num == 2: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False)) + if sub_num == 3: + self.proj = nn.Sequential( + ConvBNLayer( + in_channels=in_channels, + out_channels=embed_dim // 4, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 4, + out_channels=embed_dim // 2, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False), + ConvBNLayer( + in_channels=embed_dim // 2, + out_channels=embed_dim, + kernel_size=3, + stride=2, + padding=1, + act=nn.GELU, + bias_attr=False)) + + def forward(self, x): + B, C, H, W = x.shape + assert H == self.img_size[0] and W == self.img_size[1], \ + f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})." + x = self.proj(x).flatten(2).permute(0, 2, 1) + return x + + +class SubSample(nn.Module): + def __init__(self, + in_channels, + out_channels, + types='Pool', + stride=(2, 1), + sub_norm='nn.LayerNorm', + act=None): + super().__init__() + self.types = types + if types == 'Pool': + self.avgpool = nn.AvgPool2d( + kernel_size=(3, 5), stride=stride, padding=(1, 2)) + self.maxpool = nn.MaxPool2d( + kernel_size=(3, 5), stride=stride, padding=(1, 2)) + self.proj = nn.Linear(in_channels, out_channels) + else: + self.conv = nn.Conv2d( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + # weight_attr=ParamAttr(initializer=KaimingNormal()) + ) + self.norm = eval(sub_norm)(out_channels) + if act is not None: + self.act = act() + else: + self.act = None + + def forward(self, x): + + if self.types == 'Pool': + x1 = self.avgpool(x) + x2 = self.maxpool(x) + x = (x1 + x2) * 0.5 + out = self.proj(x.flatten(2).permute((0, 2, 1))) + else: + x = self.conv(x) + out = x.flatten(2).permute((0, 2, 1)) + out = self.norm(out) + if self.act is not None: + out = self.act(out) + + return out + + +class SVTRNet(nn.Module): + def __init__( + self, + img_size=[48, 100], + in_channels=3, + embed_dim=[64, 128, 256], + depth=[3, 6, 3], + num_heads=[2, 4, 8], + mixer=['Local'] * 6 + ['Global'] * + 6, # Local atten, Global atten, Conv + local_mixer=[[7, 11], [7, 11], [7, 11]], + patch_merging='Conv', # Conv, Pool, None + mlp_ratio=4, + qkv_bias=True, + qk_scale=None, + drop_rate=0., + last_drop=0.1, + attn_drop_rate=0., + drop_path_rate=0.1, + norm_layer='nn.LayerNorm', + sub_norm='nn.LayerNorm', + epsilon=1e-6, + out_channels=192, + out_char_num=25, + block_unit='Block', + act='nn.GELU', + last_stage=True, + sub_num=2, + prenorm=True, + use_lenhead=False, + **kwargs): + super().__init__() + self.img_size = img_size + self.embed_dim = embed_dim + self.out_channels = out_channels + self.prenorm = prenorm + patch_merging = None if patch_merging != 'Conv' and patch_merging != 'Pool' else patch_merging + self.patch_embed = PatchEmbed( + img_size=img_size, + in_channels=in_channels, + embed_dim=embed_dim[0], + sub_num=sub_num) + num_patches = self.patch_embed.num_patches + self.HW = [img_size[0] // (2**sub_num), img_size[1] // (2**sub_num)] + self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, embed_dim[0])) + # self.pos_embed = self.create_parameter( + # shape=[1, num_patches, embed_dim[0]], default_initializer=zeros_) + + # self.add_parameter("pos_embed", self.pos_embed) + + self.pos_drop = nn.Dropout(p=drop_rate) + Block_unit = eval(block_unit) + + dpr = np.linspace(0, drop_path_rate, sum(depth)) + self.blocks1 = nn.ModuleList( + [ + Block_unit( + dim=embed_dim[0], + num_heads=num_heads[0], + mixer=mixer[0:depth[0]][i], + HW=self.HW, + local_mixer=local_mixer[0], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[0:depth[0]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[0]) + ] + ) + if patch_merging is not None: + self.sub_sample1 = SubSample( + embed_dim[0], + embed_dim[1], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 2, self.HW[1]] + else: + HW = self.HW + self.patch_merging = patch_merging + self.blocks2 = nn.ModuleList([ + Block_unit( + dim=embed_dim[1], + num_heads=num_heads[1], + mixer=mixer[depth[0]:depth[0] + depth[1]][i], + HW=HW, + local_mixer=local_mixer[1], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0]:depth[0] + depth[1]][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[1]) + ]) + if patch_merging is not None: + self.sub_sample2 = SubSample( + embed_dim[1], + embed_dim[2], + sub_norm=sub_norm, + stride=[2, 1], + types=patch_merging) + HW = [self.HW[0] // 4, self.HW[1]] + else: + HW = self.HW + self.blocks3 = nn.ModuleList([ + Block_unit( + dim=embed_dim[2], + num_heads=num_heads[2], + mixer=mixer[depth[0] + depth[1]:][i], + HW=HW, + local_mixer=local_mixer[2], + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop_rate, + act_layer=eval(act), + attn_drop=attn_drop_rate, + drop_path=dpr[depth[0] + depth[1]:][i], + norm_layer=norm_layer, + epsilon=epsilon, + prenorm=prenorm) for i in range(depth[2]) + ]) + self.last_stage = last_stage + if last_stage: + self.avg_pool = nn.AdaptiveAvgPool2d((1, out_char_num)) + self.last_conv = nn.Conv2d( + in_channels=embed_dim[2], + out_channels=self.out_channels, + kernel_size=1, + stride=1, + padding=0, + bias=False) + self.hardswish = nn.Hardswish() + self.dropout = nn.Dropout(p=last_drop) + if not prenorm: + self.norm = eval(norm_layer)(embed_dim[-1], epsilon=epsilon) + self.use_lenhead = use_lenhead + if use_lenhead: + self.len_conv = nn.Linear(embed_dim[2], self.out_channels) + self.hardswish_len = nn.Hardswish() + self.dropout_len = nn.Dropout( + p=last_drop) + + trunc_normal_(self.pos_embed,std=.02) + self.apply(self._init_weights) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight,std=.02) + if isinstance(m, nn.Linear) and m.bias is not None: + zeros_(m.bias) + elif isinstance(m, nn.LayerNorm): + zeros_(m.bias) + ones_(m.weight) + + def forward_features(self, x): + x = self.patch_embed(x) + x = x + self.pos_embed + x = self.pos_drop(x) + for blk in self.blocks1: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample1( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[0], self.HW[0], self.HW[1]])) + for blk in self.blocks2: + x = blk(x) + if self.patch_merging is not None: + x = self.sub_sample2( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[1], self.HW[0] // 2, self.HW[1]])) + for blk in self.blocks3: + x = blk(x) + if not self.prenorm: + x = self.norm(x) + return x + + def forward(self, x): + x = self.forward_features(x) + if self.use_lenhead: + len_x = self.len_conv(x.mean(1)) + len_x = self.dropout_len(self.hardswish_len(len_x)) + if self.last_stage: + if self.patch_merging is not None: + h = self.HW[0] // 4 + else: + h = self.HW[0] + x = self.avg_pool( + x.permute([0, 2, 1]).reshape( + [-1, self.embed_dim[2], h, self.HW[1]])) + x = self.last_conv(x) + x = self.hardswish(x) + x = self.dropout(x) + if self.use_lenhead: + return x, len_x + return x + + +if __name__=="__main__": + a = torch.rand(1,3,48,100) + svtr = SVTRNet() + + out = svtr(a) + print(svtr) + print(out.size()) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/__init__.py b/py/iopaint/model/anytext/ocr_recog/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/anytext/ocr_recog/common.py b/py/iopaint/model/anytext/ocr_recog/common.py new file mode 100644 index 0000000..a328bb0 --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/common.py @@ -0,0 +1,74 @@ + + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class Hswish(nn.Module): + def __init__(self, inplace=True): + super(Hswish, self).__init__() + self.inplace = inplace + + def forward(self, x): + return x * F.relu6(x + 3., inplace=self.inplace) / 6. + +# out = max(0, min(1, slop*x+offset)) +# paddle.fluid.layers.hard_sigmoid(x, slope=0.2, offset=0.5, name=None) +class Hsigmoid(nn.Module): + def __init__(self, inplace=True): + super(Hsigmoid, self).__init__() + self.inplace = inplace + + def forward(self, x): + # torch: F.relu6(x + 3., inplace=self.inplace) / 6. + # paddle: F.relu6(1.2 * x + 3., inplace=self.inplace) / 6. + return F.relu6(1.2 * x + 3., inplace=self.inplace) / 6. + +class GELU(nn.Module): + def __init__(self, inplace=True): + super(GELU, self).__init__() + self.inplace = inplace + + def forward(self, x): + return torch.nn.functional.gelu(x) + + +class Swish(nn.Module): + def __init__(self, inplace=True): + super(Swish, self).__init__() + self.inplace = inplace + + def forward(self, x): + if self.inplace: + x.mul_(torch.sigmoid(x)) + return x + else: + return x*torch.sigmoid(x) + + +class Activation(nn.Module): + def __init__(self, act_type, inplace=True): + super(Activation, self).__init__() + act_type = act_type.lower() + if act_type == 'relu': + self.act = nn.ReLU(inplace=inplace) + elif act_type == 'relu6': + self.act = nn.ReLU6(inplace=inplace) + elif act_type == 'sigmoid': + raise NotImplementedError + elif act_type == 'hard_sigmoid': + self.act = Hsigmoid(inplace) + elif act_type == 'hard_swish': + self.act = Hswish(inplace=inplace) + elif act_type == 'leakyrelu': + self.act = nn.LeakyReLU(inplace=inplace) + elif act_type == 'gelu': + self.act = GELU(inplace=inplace) + elif act_type == 'swish': + self.act = Swish(inplace=inplace) + else: + raise NotImplementedError + + def forward(self, inputs): + return self.act(inputs) \ No newline at end of file diff --git a/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt b/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt new file mode 100644 index 0000000..84b885d --- /dev/null +++ b/py/iopaint/model/anytext/ocr_recog/ppocr_keys_v1.txt @@ -0,0 +1,6623 @@ +' +疗 +绚 +诚 +娇 +溜 +题 +贿 +者 +廖 +更 +纳 +加 +奉 +公 +一 +就 +汴 +计 +与 +路 +房 +原 +妇 +2 +0 +8 +- +7 +其 +> +: +] +, +, +骑 +刈 +全 +消 +昏 +傈 +安 +久 +钟 +嗅 +不 +影 +处 +驽 +蜿 +资 +关 +椤 +地 +瘸 +专 +问 +忖 +票 +嫉 +炎 +韵 +要 +月 +田 +节 +陂 +鄙 +捌 +备 +拳 +伺 +眼 +网 +盎 +大 +傍 +心 +东 +愉 +汇 +蹿 +科 +每 +业 +里 +航 +晏 +字 +平 +录 +先 +1 +3 +彤 +鲶 +产 +稍 +督 +腴 +有 +象 +岳 +注 +绍 +在 +泺 +文 +定 +核 +名 +水 +过 +理 +让 +偷 +率 +等 +这 +发 +” +为 +含 +肥 +酉 +相 +鄱 +七 +编 +猥 +锛 +日 +镀 +蒂 +掰 +倒 +辆 +栾 +栗 +综 +涩 +州 +雌 +滑 +馀 +了 +机 +块 +司 +宰 +甙 +兴 +矽 +抚 +保 +用 +沧 +秩 +如 +收 +息 +滥 +页 +疑 +埠 +! +! +姥 +异 +橹 +钇 +向 +下 +跄 +的 +椴 +沫 +国 +绥 +獠 +报 +开 +民 +蜇 +何 +分 +凇 +长 +讥 +藏 +掏 +施 +羽 +中 +讲 +派 +嘟 +人 +提 +浼 +间 +世 +而 +古 +多 +倪 +唇 +饯 +控 +庚 +首 +赛 +蜓 +味 +断 +制 +觉 +技 +替 +艰 +溢 +潮 +夕 +钺 +外 +摘 +枋 +动 +双 +单 +啮 +户 +枇 +确 +锦 +曜 +杜 +或 +能 +效 +霜 +盒 +然 +侗 +电 +晁 +放 +步 +鹃 +新 +杖 +蜂 +吒 +濂 +瞬 +评 +总 +隍 +对 +独 +合 +也 +是 +府 +青 +天 +诲 +墙 +组 +滴 +级 +邀 +帘 +示 +已 +时 +骸 +仄 +泅 +和 +遨 +店 +雇 +疫 +持 +巍 +踮 +境 +只 +亨 +目 +鉴 +崤 +闲 +体 +泄 +杂 +作 +般 +轰 +化 +解 +迂 +诿 +蛭 +璀 +腾 +告 +版 +服 +省 +师 +小 +规 +程 +线 +海 +办 +引 +二 +桧 +牌 +砺 +洄 +裴 +修 +图 +痫 +胡 +许 +犊 +事 +郛 +基 +柴 +呼 +食 +研 +奶 +律 +蛋 +因 +葆 +察 +戏 +褒 +戒 +再 +李 +骁 +工 +貂 +油 +鹅 +章 +啄 +休 +场 +给 +睡 +纷 +豆 +器 +捎 +说 +敏 +学 +会 +浒 +设 +诊 +格 +廓 +查 +来 +霓 +室 +溆 +¢ +诡 +寥 +焕 +舜 +柒 +狐 +回 +戟 +砾 +厄 +实 +翩 +尿 +五 +入 +径 +惭 +喹 +股 +宇 +篝 +| +; +美 +期 +云 +九 +祺 +扮 +靠 +锝 +槌 +系 +企 +酰 +阊 +暂 +蚕 +忻 +豁 +本 +羹 +执 +条 +钦 +H +獒 +限 +进 +季 +楦 +于 +芘 +玖 +铋 +茯 +未 +答 +粘 +括 +样 +精 +欠 +矢 +甥 +帷 +嵩 +扣 +令 +仔 +风 +皈 +行 +支 +部 +蓉 +刮 +站 +蜡 +救 +钊 +汗 +松 +嫌 +成 +可 +. +鹤 +院 +从 +交 +政 +怕 +活 +调 +球 +局 +验 +髌 +第 +韫 +谗 +串 +到 +圆 +年 +米 +/ +* +友 +忿 +检 +区 +看 +自 +敢 +刃 +个 +兹 +弄 +流 +留 +同 +没 +齿 +星 +聆 +轼 +湖 +什 +三 +建 +蛔 +儿 +椋 +汕 +震 +颧 +鲤 +跟 +力 +情 +璺 +铨 +陪 +务 +指 +族 +训 +滦 +鄣 +濮 +扒 +商 +箱 +十 +召 +慷 +辗 +所 +莞 +管 +护 +臭 +横 +硒 +嗓 +接 +侦 +六 +露 +党 +馋 +驾 +剖 +高 +侬 +妪 +幂 +猗 +绺 +骐 +央 +酐 +孝 +筝 +课 +徇 +缰 +门 +男 +西 +项 +句 +谙 +瞒 +秃 +篇 +教 +碲 +罚 +声 +呐 +景 +前 +富 +嘴 +鳌 +稀 +免 +朋 +啬 +睐 +去 +赈 +鱼 +住 +肩 +愕 +速 +旁 +波 +厅 +健 +茼 +厥 +鲟 +谅 +投 +攸 +炔 +数 +方 +击 +呋 +谈 +绩 +别 +愫 +僚 +躬 +鹧 +胪 +炳 +招 +喇 +膨 +泵 +蹦 +毛 +结 +5 +4 +谱 +识 +陕 +粽 +婚 +拟 +构 +且 +搜 +任 +潘 +比 +郢 +妨 +醪 +陀 +桔 +碘 +扎 +选 +哈 +骷 +楷 +亿 +明 +缆 +脯 +监 +睫 +逻 +婵 +共 +赴 +淝 +凡 +惦 +及 +达 +揖 +谩 +澹 +减 +焰 +蛹 +番 +祁 +柏 +员 +禄 +怡 +峤 +龙 +白 +叽 +生 +闯 +起 +细 +装 +谕 +竟 +聚 +钙 +上 +导 +渊 +按 +艾 +辘 +挡 +耒 +盹 +饪 +臀 +记 +邮 +蕙 +受 +各 +医 +搂 +普 +滇 +朗 +茸 +带 +翻 +酚 +( +光 +堤 +墟 +蔷 +万 +幻 +〓 +瑙 +辈 +昧 +盏 +亘 +蛀 +吉 +铰 +请 +子 +假 +闻 +税 +井 +诩 +哨 +嫂 +好 +面 +琐 +校 +馊 +鬣 +缂 +营 +访 +炖 +占 +农 +缀 +否 +经 +钚 +棵 +趟 +张 +亟 +吏 +茶 +谨 +捻 +论 +迸 +堂 +玉 +信 +吧 +瞠 +乡 +姬 +寺 +咬 +溏 +苄 +皿 +意 +赉 +宝 +尔 +钰 +艺 +特 +唳 +踉 +都 +荣 +倚 +登 +荐 +丧 +奇 +涵 +批 +炭 +近 +符 +傩 +感 +道 +着 +菊 +虹 +仲 +众 +懈 +濯 +颞 +眺 +南 +释 +北 +缝 +标 +既 +茗 +整 +撼 +迤 +贲 +挎 +耱 +拒 +某 +妍 +卫 +哇 +英 +矶 +藩 +治 +他 +元 +领 +膜 +遮 +穗 +蛾 +飞 +荒 +棺 +劫 +么 +市 +火 +温 +拈 +棚 +洼 +转 +果 +奕 +卸 +迪 +伸 +泳 +斗 +邡 +侄 +涨 +屯 +萋 +胭 +氡 +崮 +枞 +惧 +冒 +彩 +斜 +手 +豚 +随 +旭 +淑 +妞 +形 +菌 +吲 +沱 +争 +驯 +歹 +挟 +兆 +柱 +传 +至 +包 +内 +响 +临 +红 +功 +弩 +衡 +寂 +禁 +老 +棍 +耆 +渍 +织 +害 +氵 +渑 +布 +载 +靥 +嗬 +虽 +苹 +咨 +娄 +库 +雉 +榜 +帜 +嘲 +套 +瑚 +亲 +簸 +欧 +边 +6 +腿 +旮 +抛 +吹 +瞳 +得 +镓 +梗 +厨 +继 +漾 +愣 +憨 +士 +策 +窑 +抑 +躯 +襟 +脏 +参 +贸 +言 +干 +绸 +鳄 +穷 +藜 +音 +折 +详 +) +举 +悍 +甸 +癌 +黎 +谴 +死 +罩 +迁 +寒 +驷 +袖 +媒 +蒋 +掘 +模 +纠 +恣 +观 +祖 +蛆 +碍 +位 +稿 +主 +澧 +跌 +筏 +京 +锏 +帝 +贴 +证 +糠 +才 +黄 +鲸 +略 +炯 +饱 +四 +出 +园 +犀 +牧 +容 +汉 +杆 +浈 +汰 +瑷 +造 +虫 +瘩 +怪 +驴 +济 +应 +花 +沣 +谔 +夙 +旅 +价 +矿 +以 +考 +s +u +呦 +晒 +巡 +茅 +准 +肟 +瓴 +詹 +仟 +褂 +译 +桌 +混 +宁 +怦 +郑 +抿 +些 +余 +鄂 +饴 +攒 +珑 +群 +阖 +岔 +琨 +藓 +预 +环 +洮 +岌 +宀 +杲 +瀵 +最 +常 +囡 +周 +踊 +女 +鼓 +袭 +喉 +简 +范 +薯 +遐 +疏 +粱 +黜 +禧 +法 +箔 +斤 +遥 +汝 +奥 +直 +贞 +撑 +置 +绱 +集 +她 +馅 +逗 +钧 +橱 +魉 +[ +恙 +躁 +唤 +9 +旺 +膘 +待 +脾 +惫 +购 +吗 +依 +盲 +度 +瘿 +蠖 +俾 +之 +镗 +拇 +鲵 +厝 +簧 +续 +款 +展 +啃 +表 +剔 +品 +钻 +腭 +损 +清 +锶 +统 +涌 +寸 +滨 +贪 +链 +吠 +冈 +伎 +迥 +咏 +吁 +览 +防 +迅 +失 +汾 +阔 +逵 +绀 +蔑 +列 +川 +凭 +努 +熨 +揪 +利 +俱 +绉 +抢 +鸨 +我 +即 +责 +膦 +易 +毓 +鹊 +刹 +玷 +岿 +空 +嘞 +绊 +排 +术 +估 +锷 +违 +们 +苟 +铜 +播 +肘 +件 +烫 +审 +鲂 +广 +像 +铌 +惰 +铟 +巳 +胍 +鲍 +康 +憧 +色 +恢 +想 +拷 +尤 +疳 +知 +S +Y +F +D +A +峄 +裕 +帮 +握 +搔 +氐 +氘 +难 +墒 +沮 +雨 +叁 +缥 +悴 +藐 +湫 +娟 +苑 +稠 +颛 +簇 +后 +阕 +闭 +蕤 +缚 +怎 +佞 +码 +嘤 +蔡 +痊 +舱 +螯 +帕 +赫 +昵 +升 +烬 +岫 +、 +疵 +蜻 +髁 +蕨 +隶 +烛 +械 +丑 +盂 +梁 +强 +鲛 +由 +拘 +揉 +劭 +龟 +撤 +钩 +呕 +孛 +费 +妻 +漂 +求 +阑 +崖 +秤 +甘 +通 +深 +补 +赃 +坎 +床 +啪 +承 +吼 +量 +暇 +钼 +烨 +阂 +擎 +脱 +逮 +称 +P +神 +属 +矗 +华 +届 +狍 +葑 +汹 +育 +患 +窒 +蛰 +佼 +静 +槎 +运 +鳗 +庆 +逝 +曼 +疱 +克 +代 +官 +此 +麸 +耧 +蚌 +晟 +例 +础 +榛 +副 +测 +唰 +缢 +迹 +灬 +霁 +身 +岁 +赭 +扛 +又 +菡 +乜 +雾 +板 +读 +陷 +徉 +贯 +郁 +虑 +变 +钓 +菜 +圾 +现 +琢 +式 +乐 +维 +渔 +浜 +左 +吾 +脑 +钡 +警 +T +啵 +拴 +偌 +漱 +湿 +硕 +止 +骼 +魄 +积 +燥 +联 +踢 +玛 +则 +窿 +见 +振 +畿 +送 +班 +钽 +您 +赵 +刨 +印 +讨 +踝 +籍 +谡 +舌 +崧 +汽 +蔽 +沪 +酥 +绒 +怖 +财 +帖 +肱 +私 +莎 +勋 +羔 +霸 +励 +哼 +帐 +将 +帅 +渠 +纪 +婴 +娩 +岭 +厘 +滕 +吻 +伤 +坝 +冠 +戊 +隆 +瘁 +介 +涧 +物 +黍 +并 +姗 +奢 +蹑 +掣 +垸 +锴 +命 +箍 +捉 +病 +辖 +琰 +眭 +迩 +艘 +绌 +繁 +寅 +若 +毋 +思 +诉 +类 +诈 +燮 +轲 +酮 +狂 +重 +反 +职 +筱 +县 +委 +磕 +绣 +奖 +晋 +濉 +志 +徽 +肠 +呈 +獐 +坻 +口 +片 +碰 +几 +村 +柿 +劳 +料 +获 +亩 +惕 +晕 +厌 +号 +罢 +池 +正 +鏖 +煨 +家 +棕 +复 +尝 +懋 +蜥 +锅 +岛 +扰 +队 +坠 +瘾 +钬 +@ +卧 +疣 +镇 +譬 +冰 +彷 +频 +黯 +据 +垄 +采 +八 +缪 +瘫 +型 +熹 +砰 +楠 +襁 +箐 +但 +嘶 +绳 +啤 +拍 +盥 +穆 +傲 +洗 +盯 +塘 +怔 +筛 +丿 +台 +恒 +喂 +葛 +永 +¥ +烟 +酒 +桦 +书 +砂 +蚝 +缉 +态 +瀚 +袄 +圳 +轻 +蛛 +超 +榧 +遛 +姒 +奘 +铮 +右 +荽 +望 +偻 +卡 +丶 +氰 +附 +做 +革 +索 +戚 +坨 +桷 +唁 +垅 +榻 +岐 +偎 +坛 +莨 +山 +殊 +微 +骇 +陈 +爨 +推 +嗝 +驹 +澡 +藁 +呤 +卤 +嘻 +糅 +逛 +侵 +郓 +酌 +德 +摇 +※ +鬃 +被 +慨 +殡 +羸 +昌 +泡 +戛 +鞋 +河 +宪 +沿 +玲 +鲨 +翅 +哽 +源 +铅 +语 +照 +邯 +址 +荃 +佬 +顺 +鸳 +町 +霭 +睾 +瓢 +夸 +椁 +晓 +酿 +痈 +咔 +侏 +券 +噎 +湍 +签 +嚷 +离 +午 +尚 +社 +锤 +背 +孟 +使 +浪 +缦 +潍 +鞅 +军 +姹 +驶 +笑 +鳟 +鲁 +》 +孽 +钜 +绿 +洱 +礴 +焯 +椰 +颖 +囔 +乌 +孔 +巴 +互 +性 +椽 +哞 +聘 +昨 +早 +暮 +胶 +炀 +隧 +低 +彗 +昝 +铁 +呓 +氽 +藉 +喔 +癖 +瑗 +姨 +权 +胱 +韦 +堑 +蜜 +酋 +楝 +砝 +毁 +靓 +歙 +锲 +究 +屋 +喳 +骨 +辨 +碑 +武 +鸠 +宫 +辜 +烊 +适 +坡 +殃 +培 +佩 +供 +走 +蜈 +迟 +翼 +况 +姣 +凛 +浔 +吃 +飘 +债 +犟 +金 +促 +苛 +崇 +坂 +莳 +畔 +绂 +兵 +蠕 +斋 +根 +砍 +亢 +欢 +恬 +崔 +剁 +餐 +榫 +快 +扶 +‖ +濒 +缠 +鳜 +当 +彭 +驭 +浦 +篮 +昀 +锆 +秸 +钳 +弋 +娣 +瞑 +夷 +龛 +苫 +拱 +致 +% +嵊 +障 +隐 +弑 +初 +娓 +抉 +汩 +累 +蓖 +" +唬 +助 +苓 +昙 +押 +毙 +破 +城 +郧 +逢 +嚏 +獭 +瞻 +溱 +婿 +赊 +跨 +恼 +璧 +萃 +姻 +貉 +灵 +炉 +密 +氛 +陶 +砸 +谬 +衔 +点 +琛 +沛 +枳 +层 +岱 +诺 +脍 +榈 +埂 +征 +冷 +裁 +打 +蹴 +素 +瘘 +逞 +蛐 +聊 +激 +腱 +萘 +踵 +飒 +蓟 +吆 +取 +咙 +簋 +涓 +矩 +曝 +挺 +揣 +座 +你 +史 +舵 +焱 +尘 +苏 +笈 +脚 +溉 +榨 +诵 +樊 +邓 +焊 +义 +庶 +儋 +蟋 +蒲 +赦 +呷 +杞 +诠 +豪 +还 +试 +颓 +茉 +太 +除 +紫 +逃 +痴 +草 +充 +鳕 +珉 +祗 +墨 +渭 +烩 +蘸 +慕 +璇 +镶 +穴 +嵘 +恶 +骂 +险 +绋 +幕 +碉 +肺 +戳 +刘 +潞 +秣 +纾 +潜 +銮 +洛 +须 +罘 +销 +瘪 +汞 +兮 +屉 +r +林 +厕 +质 +探 +划 +狸 +殚 +善 +煊 +烹 +〒 +锈 +逯 +宸 +辍 +泱 +柚 +袍 +远 +蹋 +嶙 +绝 +峥 +娥 +缍 +雀 +徵 +认 +镱 +谷 += +贩 +勉 +撩 +鄯 +斐 +洋 +非 +祚 +泾 +诒 +饿 +撬 +威 +晷 +搭 +芍 +锥 +笺 +蓦 +候 +琊 +档 +礁 +沼 +卵 +荠 +忑 +朝 +凹 +瑞 +头 +仪 +弧 +孵 +畏 +铆 +突 +衲 +车 +浩 +气 +茂 +悖 +厢 +枕 +酝 +戴 +湾 +邹 +飚 +攘 +锂 +写 +宵 +翁 +岷 +无 +喜 +丈 +挑 +嗟 +绛 +殉 +议 +槽 +具 +醇 +淞 +笃 +郴 +阅 +饼 +底 +壕 +砚 +弈 +询 +缕 +庹 +翟 +零 +筷 +暨 +舟 +闺 +甯 +撞 +麂 +茌 +蔼 +很 +珲 +捕 +棠 +角 +阉 +媛 +娲 +诽 +剿 +尉 +爵 +睬 +韩 +诰 +匣 +危 +糍 +镯 +立 +浏 +阳 +少 +盆 +舔 +擘 +匪 +申 +尬 +铣 +旯 +抖 +赘 +瓯 +居 +ˇ +哮 +游 +锭 +茏 +歌 +坏 +甚 +秒 +舞 +沙 +仗 +劲 +潺 +阿 +燧 +郭 +嗖 +霏 +忠 +材 +奂 +耐 +跺 +砀 +输 +岖 +媳 +氟 +极 +摆 +灿 +今 +扔 +腻 +枝 +奎 +药 +熄 +吨 +话 +q +额 +慑 +嘌 +协 +喀 +壳 +埭 +视 +著 +於 +愧 +陲 +翌 +峁 +颅 +佛 +腹 +聋 +侯 +咎 +叟 +秀 +颇 +存 +较 +罪 +哄 +岗 +扫 +栏 +钾 +羌 +己 +璨 +枭 +霉 +煌 +涸 +衿 +键 +镝 +益 +岢 +奏 +连 +夯 +睿 +冥 +均 +糖 +狞 +蹊 +稻 +爸 +刿 +胥 +煜 +丽 +肿 +璃 +掸 +跚 +灾 +垂 +樾 +濑 +乎 +莲 +窄 +犹 +撮 +战 +馄 +软 +络 +显 +鸢 +胸 +宾 +妲 +恕 +埔 +蝌 +份 +遇 +巧 +瞟 +粒 +恰 +剥 +桡 +博 +讯 +凯 +堇 +阶 +滤 +卖 +斌 +骚 +彬 +兑 +磺 +樱 +舷 +两 +娱 +福 +仃 +差 +找 +桁 +÷ +净 +把 +阴 +污 +戬 +雷 +碓 +蕲 +楚 +罡 +焖 +抽 +妫 +咒 +仑 +闱 +尽 +邑 +菁 +爱 +贷 +沥 +鞑 +牡 +嗉 +崴 +骤 +塌 +嗦 +订 +拮 +滓 +捡 +锻 +次 +坪 +杩 +臃 +箬 +融 +珂 +鹗 +宗 +枚 +降 +鸬 +妯 +阄 +堰 +盐 +毅 +必 +杨 +崃 +俺 +甬 +状 +莘 +货 +耸 +菱 +腼 +铸 +唏 +痤 +孚 +澳 +懒 +溅 +翘 +疙 +杷 +淼 +缙 +骰 +喊 +悉 +砻 +坷 +艇 +赁 +界 +谤 +纣 +宴 +晃 +茹 +归 +饭 +梢 +铡 +街 +抄 +肼 +鬟 +苯 +颂 +撷 +戈 +炒 +咆 +茭 +瘙 +负 +仰 +客 +琉 +铢 +封 +卑 +珥 +椿 +镧 +窨 +鬲 +寿 +御 +袤 +铃 +萎 +砖 +餮 +脒 +裳 +肪 +孕 +嫣 +馗 +嵇 +恳 +氯 +江 +石 +褶 +冢 +祸 +阻 +狈 +羞 +银 +靳 +透 +咳 +叼 +敷 +芷 +啥 +它 +瓤 +兰 +痘 +懊 +逑 +肌 +往 +捺 +坊 +甩 +呻 +〃 +沦 +忘 +膻 +祟 +菅 +剧 +崆 +智 +坯 +臧 +霍 +墅 +攻 +眯 +倘 +拢 +骠 +铐 +庭 +岙 +瓠 +′ +缺 +泥 +迢 +捶 +? +? +郏 +喙 +掷 +沌 +纯 +秘 +种 +听 +绘 +固 +螨 +团 +香 +盗 +妒 +埚 +蓝 +拖 +旱 +荞 +铀 +血 +遏 +汲 +辰 +叩 +拽 +幅 +硬 +惶 +桀 +漠 +措 +泼 +唑 +齐 +肾 +念 +酱 +虚 +屁 +耶 +旗 +砦 +闵 +婉 +馆 +拭 +绅 +韧 +忏 +窝 +醋 +葺 +顾 +辞 +倜 +堆 +辋 +逆 +玟 +贱 +疾 +董 +惘 +倌 +锕 +淘 +嘀 +莽 +俭 +笏 +绑 +鲷 +杈 +择 +蟀 +粥 +嗯 +驰 +逾 +案 +谪 +褓 +胫 +哩 +昕 +颚 +鲢 +绠 +躺 +鹄 +崂 +儒 +俨 +丝 +尕 +泌 +啊 +萸 +彰 +幺 +吟 +骄 +苣 +弦 +脊 +瑰 +〈 +诛 +镁 +析 +闪 +剪 +侧 +哟 +框 +螃 +守 +嬗 +燕 +狭 +铈 +缮 +概 +迳 +痧 +鲲 +俯 +售 +笼 +痣 +扉 +挖 +满 +咋 +援 +邱 +扇 +歪 +便 +玑 +绦 +峡 +蛇 +叨 +〖 +泽 +胃 +斓 +喋 +怂 +坟 +猪 +该 +蚬 +炕 +弥 +赞 +棣 +晔 +娠 +挲 +狡 +创 +疖 +铕 +镭 +稷 +挫 +弭 +啾 +翔 +粉 +履 +苘 +哦 +楼 +秕 +铂 +土 +锣 +瘟 +挣 +栉 +习 +享 +桢 +袅 +磨 +桂 +谦 +延 +坚 +蔚 +噗 +署 +谟 +猬 +钎 +恐 +嬉 +雒 +倦 +衅 +亏 +璩 +睹 +刻 +殿 +王 +算 +雕 +麻 +丘 +柯 +骆 +丸 +塍 +谚 +添 +鲈 +垓 +桎 +蚯 +芥 +予 +飕 +镦 +谌 +窗 +醚 +菀 +亮 +搪 +莺 +蒿 +羁 +足 +J +真 +轶 +悬 +衷 +靛 +翊 +掩 +哒 +炅 +掐 +冼 +妮 +l +谐 +稚 +荆 +擒 +犯 +陵 +虏 +浓 +崽 +刍 +陌 +傻 +孜 +千 +靖 +演 +矜 +钕 +煽 +杰 +酗 +渗 +伞 +栋 +俗 +泫 +戍 +罕 +沾 +疽 +灏 +煦 +芬 +磴 +叱 +阱 +榉 +湃 +蜀 +叉 +醒 +彪 +租 +郡 +篷 +屎 +良 +垢 +隗 +弱 +陨 +峪 +砷 +掴 +颁 +胎 +雯 +绵 +贬 +沐 +撵 +隘 +篙 +暖 +曹 +陡 +栓 +填 +臼 +彦 +瓶 +琪 +潼 +哪 +鸡 +摩 +啦 +俟 +锋 +域 +耻 +蔫 +疯 +纹 +撇 +毒 +绶 +痛 +酯 +忍 +爪 +赳 +歆 +嘹 +辕 +烈 +册 +朴 +钱 +吮 +毯 +癜 +娃 +谀 +邵 +厮 +炽 +璞 +邃 +丐 +追 +词 +瓒 +忆 +轧 +芫 +谯 +喷 +弟 +半 +冕 +裙 +掖 +墉 +绮 +寝 +苔 +势 +顷 +褥 +切 +衮 +君 +佳 +嫒 +蚩 +霞 +佚 +洙 +逊 +镖 +暹 +唛 +& +殒 +顶 +碗 +獗 +轭 +铺 +蛊 +废 +恹 +汨 +崩 +珍 +那 +杵 +曲 +纺 +夏 +薰 +傀 +闳 +淬 +姘 +舀 +拧 +卷 +楂 +恍 +讪 +厩 +寮 +篪 +赓 +乘 +灭 +盅 +鞣 +沟 +慎 +挂 +饺 +鼾 +杳 +树 +缨 +丛 +絮 +娌 +臻 +嗳 +篡 +侩 +述 +衰 +矛 +圈 +蚜 +匕 +筹 +匿 +濞 +晨 +叶 +骋 +郝 +挚 +蚴 +滞 +增 +侍 +描 +瓣 +吖 +嫦 +蟒 +匾 +圣 +赌 +毡 +癞 +恺 +百 +曳 +需 +篓 +肮 +庖 +帏 +卿 +驿 +遗 +蹬 +鬓 +骡 +歉 +芎 +胳 +屐 +禽 +烦 +晌 +寄 +媾 +狄 +翡 +苒 +船 +廉 +终 +痞 +殇 +々 +畦 +饶 +改 +拆 +悻 +萄 +£ +瓿 +乃 +訾 +桅 +匮 +溧 +拥 +纱 +铍 +骗 +蕃 +龋 +缬 +父 +佐 +疚 +栎 +醍 +掳 +蓄 +x +惆 +颜 +鲆 +榆 +〔 +猎 +敌 +暴 +谥 +鲫 +贾 +罗 +玻 +缄 +扦 +芪 +癣 +落 +徒 +臾 +恿 +猩 +托 +邴 +肄 +牵 +春 +陛 +耀 +刊 +拓 +蓓 +邳 +堕 +寇 +枉 +淌 +啡 +湄 +兽 +酷 +萼 +碚 +濠 +萤 +夹 +旬 +戮 +梭 +琥 +椭 +昔 +勺 +蜊 +绐 +晚 +孺 +僵 +宣 +摄 +冽 +旨 +萌 +忙 +蚤 +眉 +噼 +蟑 +付 +契 +瓜 +悼 +颡 +壁 +曾 +窕 +颢 +澎 +仿 +俑 +浑 +嵌 +浣 +乍 +碌 +褪 +乱 +蔟 +隙 +玩 +剐 +葫 +箫 +纲 +围 +伐 +决 +伙 +漩 +瑟 +刑 +肓 +镳 +缓 +蹭 +氨 +皓 +典 +畲 +坍 +铑 +檐 +塑 +洞 +倬 +储 +胴 +淳 +戾 +吐 +灼 +惺 +妙 +毕 +珐 +缈 +虱 +盖 +羰 +鸿 +磅 +谓 +髅 +娴 +苴 +唷 +蚣 +霹 +抨 +贤 +唠 +犬 +誓 +逍 +庠 +逼 +麓 +籼 +釉 +呜 +碧 +秧 +氩 +摔 +霄 +穸 +纨 +辟 +妈 +映 +完 +牛 +缴 +嗷 +炊 +恩 +荔 +茆 +掉 +紊 +慌 +莓 +羟 +阙 +萁 +磐 +另 +蕹 +辱 +鳐 +湮 +吡 +吩 +唐 +睦 +垠 +舒 +圜 +冗 +瞿 +溺 +芾 +囱 +匠 +僳 +汐 +菩 +饬 +漓 +黑 +霰 +浸 +濡 +窥 +毂 +蒡 +兢 +驻 +鹉 +芮 +诙 +迫 +雳 +厂 +忐 +臆 +猴 +鸣 +蚪 +栈 +箕 +羡 +渐 +莆 +捍 +眈 +哓 +趴 +蹼 +埕 +嚣 +骛 +宏 +淄 +斑 +噜 +严 +瑛 +垃 +椎 +诱 +压 +庾 +绞 +焘 +廿 +抡 +迄 +棘 +夫 +纬 +锹 +眨 +瞌 +侠 +脐 +竞 +瀑 +孳 +骧 +遁 +姜 +颦 +荪 +滚 +萦 +伪 +逸 +粳 +爬 +锁 +矣 +役 +趣 +洒 +颔 +诏 +逐 +奸 +甭 +惠 +攀 +蹄 +泛 +尼 +拼 +阮 +鹰 +亚 +颈 +惑 +勒 +〉 +际 +肛 +爷 +刚 +钨 +丰 +养 +冶 +鲽 +辉 +蔻 +画 +覆 +皴 +妊 +麦 +返 +醉 +皂 +擀 +〗 +酶 +凑 +粹 +悟 +诀 +硖 +港 +卜 +z +杀 +涕 +± +舍 +铠 +抵 +弛 +段 +敝 +镐 +奠 +拂 +轴 +跛 +袱 +e +t +沉 +菇 +俎 +薪 +峦 +秭 +蟹 +历 +盟 +菠 +寡 +液 +肢 +喻 +染 +裱 +悱 +抱 +氙 +赤 +捅 +猛 +跑 +氮 +谣 +仁 +尺 +辊 +窍 +烙 +衍 +架 +擦 +倏 +璐 +瑁 +币 +楞 +胖 +夔 +趸 +邛 +惴 +饕 +虔 +蝎 +§ +哉 +贝 +宽 +辫 +炮 +扩 +饲 +籽 +魏 +菟 +锰 +伍 +猝 +末 +琳 +哚 +蛎 +邂 +呀 +姿 +鄞 +却 +歧 +仙 +恸 +椐 +森 +牒 +寤 +袒 +婆 +虢 +雅 +钉 +朵 +贼 +欲 +苞 +寰 +故 +龚 +坭 +嘘 +咫 +礼 +硷 +兀 +睢 +汶 +’ +铲 +烧 +绕 +诃 +浃 +钿 +哺 +柜 +讼 +颊 +璁 +腔 +洽 +咐 +脲 +簌 +筠 +镣 +玮 +鞠 +谁 +兼 +姆 +挥 +梯 +蝴 +谘 +漕 +刷 +躏 +宦 +弼 +b +垌 +劈 +麟 +莉 +揭 +笙 +渎 +仕 +嗤 +仓 +配 +怏 +抬 +错 +泯 +镊 +孰 +猿 +邪 +仍 +秋 +鼬 +壹 +歇 +吵 +炼 +< +尧 +射 +柬 +廷 +胧 +霾 +凳 +隋 +肚 +浮 +梦 +祥 +株 +堵 +退 +L +鹫 +跎 +凶 +毽 +荟 +炫 +栩 +玳 +甜 +沂 +鹿 +顽 +伯 +爹 +赔 +蛴 +徐 +匡 +欣 +狰 +缸 +雹 +蟆 +疤 +默 +沤 +啜 +痂 +衣 +禅 +w +i +h +辽 +葳 +黝 +钗 +停 +沽 +棒 +馨 +颌 +肉 +吴 +硫 +悯 +劾 +娈 +马 +啧 +吊 +悌 +镑 +峭 +帆 +瀣 +涉 +咸 +疸 +滋 +泣 +翦 +拙 +癸 +钥 +蜒 ++ +尾 +庄 +凝 +泉 +婢 +渴 +谊 +乞 +陆 +锉 +糊 +鸦 +淮 +I +B +N +晦 +弗 +乔 +庥 +葡 +尻 +席 +橡 +傣 +渣 +拿 +惩 +麋 +斛 +缃 +矮 +蛏 +岘 +鸽 +姐 +膏 +催 +奔 +镒 +喱 +蠡 +摧 +钯 +胤 +柠 +拐 +璋 +鸥 +卢 +荡 +倾 +^ +_ +珀 +逄 +萧 +塾 +掇 +贮 +笆 +聂 +圃 +冲 +嵬 +M +滔 +笕 +值 +炙 +偶 +蜱 +搐 +梆 +汪 +蔬 +腑 +鸯 +蹇 +敞 +绯 +仨 +祯 +谆 +梧 +糗 +鑫 +啸 +豺 +囹 +猾 +巢 +柄 +瀛 +筑 +踌 +沭 +暗 +苁 +鱿 +蹉 +脂 +蘖 +牢 +热 +木 +吸 +溃 +宠 +序 +泞 +偿 +拜 +檩 +厚 +朐 +毗 +螳 +吞 +媚 +朽 +担 +蝗 +橘 +畴 +祈 +糟 +盱 +隼 +郜 +惜 +珠 +裨 +铵 +焙 +琚 +唯 +咚 +噪 +骊 +丫 +滢 +勤 +棉 +呸 +咣 +淀 +隔 +蕾 +窈 +饨 +挨 +煅 +短 +匙 +粕 +镜 +赣 +撕 +墩 +酬 +馁 +豌 +颐 +抗 +酣 +氓 +佑 +搁 +哭 +递 +耷 +涡 +桃 +贻 +碣 +截 +瘦 +昭 +镌 +蔓 +氚 +甲 +猕 +蕴 +蓬 +散 +拾 +纛 +狼 +猷 +铎 +埋 +旖 +矾 +讳 +囊 +糜 +迈 +粟 +蚂 +紧 +鲳 +瘢 +栽 +稼 +羊 +锄 +斟 +睁 +桥 +瓮 +蹙 +祉 +醺 +鼻 +昱 +剃 +跳 +篱 +跷 +蒜 +翎 +宅 +晖 +嗑 +壑 +峻 +癫 +屏 +狠 +陋 +袜 +途 +憎 +祀 +莹 +滟 +佶 +溥 +臣 +约 +盛 +峰 +磁 +慵 +婪 +拦 +莅 +朕 +鹦 +粲 +裤 +哎 +疡 +嫖 +琵 +窟 +堪 +谛 +嘉 +儡 +鳝 +斩 +郾 +驸 +酊 +妄 +胜 +贺 +徙 +傅 +噌 +钢 +栅 +庇 +恋 +匝 +巯 +邈 +尸 +锚 +粗 +佟 +蛟 +薹 +纵 +蚊 +郅 +绢 +锐 +苗 +俞 +篆 +淆 +膀 +鲜 +煎 +诶 +秽 +寻 +涮 +刺 +怀 +噶 +巨 +褰 +魅 +灶 +灌 +桉 +藕 +谜 +舸 +薄 +搀 +恽 +借 +牯 +痉 +渥 +愿 +亓 +耘 +杠 +柩 +锔 +蚶 +钣 +珈 +喘 +蹒 +幽 +赐 +稗 +晤 +莱 +泔 +扯 +肯 +菪 +裆 +腩 +豉 +疆 +骜 +腐 +倭 +珏 +唔 +粮 +亡 +润 +慰 +伽 +橄 +玄 +誉 +醐 +胆 +龊 +粼 +塬 +陇 +彼 +削 +嗣 +绾 +芽 +妗 +垭 +瘴 +爽 +薏 +寨 +龈 +泠 +弹 +赢 +漪 +猫 +嘧 +涂 +恤 +圭 +茧 +烽 +屑 +痕 +巾 +赖 +荸 +凰 +腮 +畈 +亵 +蹲 +偃 +苇 +澜 +艮 +换 +骺 +烘 +苕 +梓 +颉 +肇 +哗 +悄 +氤 +涠 +葬 +屠 +鹭 +植 +竺 +佯 +诣 +鲇 +瘀 +鲅 +邦 +移 +滁 +冯 +耕 +癔 +戌 +茬 +沁 +巩 +悠 +湘 +洪 +痹 +锟 +循 +谋 +腕 +鳃 +钠 +捞 +焉 +迎 +碱 +伫 +急 +榷 +奈 +邝 +卯 +辄 +皲 +卟 +醛 +畹 +忧 +稳 +雄 +昼 +缩 +阈 +睑 +扌 +耗 +曦 +涅 +捏 +瞧 +邕 +淖 +漉 +铝 +耦 +禹 +湛 +喽 +莼 +琅 +诸 +苎 +纂 +硅 +始 +嗨 +傥 +燃 +臂 +赅 +嘈 +呆 +贵 +屹 +壮 +肋 +亍 +蚀 +卅 +豹 +腆 +邬 +迭 +浊 +} +童 +螂 +捐 +圩 +勐 +触 +寞 +汊 +壤 +荫 +膺 +渌 +芳 +懿 +遴 +螈 +泰 +蓼 +蛤 +茜 +舅 +枫 +朔 +膝 +眙 +避 +梅 +判 +鹜 +璜 +牍 +缅 +垫 +藻 +黔 +侥 +惚 +懂 +踩 +腰 +腈 +札 +丞 +唾 +慈 +顿 +摹 +荻 +琬 +~ +斧 +沈 +滂 +胁 +胀 +幄 +莜 +Z +匀 +鄄 +掌 +绰 +茎 +焚 +赋 +萱 +谑 +汁 +铒 +瞎 +夺 +蜗 +野 +娆 +冀 +弯 +篁 +懵 +灞 +隽 +芡 +脘 +俐 +辩 +芯 +掺 +喏 +膈 +蝈 +觐 +悚 +踹 +蔗 +熠 +鼠 +呵 +抓 +橼 +峨 +畜 +缔 +禾 +崭 +弃 +熊 +摒 +凸 +拗 +穹 +蒙 +抒 +祛 +劝 +闫 +扳 +阵 +醌 +踪 +喵 +侣 +搬 +仅 +荧 +赎 +蝾 +琦 +买 +婧 +瞄 +寓 +皎 +冻 +赝 +箩 +莫 +瞰 +郊 +笫 +姝 +筒 +枪 +遣 +煸 +袋 +舆 +痱 +涛 +母 +〇 +启 +践 +耙 +绲 +盘 +遂 +昊 +搞 +槿 +诬 +纰 +泓 +惨 +檬 +亻 +越 +C +o +憩 +熵 +祷 +钒 +暧 +塔 +阗 +胰 +咄 +娶 +魔 +琶 +钞 +邻 +扬 +杉 +殴 +咽 +弓 +〆 +髻 +】 +吭 +揽 +霆 +拄 +殖 +脆 +彻 +岩 +芝 +勃 +辣 +剌 +钝 +嘎 +甄 +佘 +皖 +伦 +授 +徕 +憔 +挪 +皇 +庞 +稔 +芜 +踏 +溴 +兖 +卒 +擢 +饥 +鳞 +煲 +‰ +账 +颗 +叻 +斯 +捧 +鳍 +琮 +讹 +蛙 +纽 +谭 +酸 +兔 +莒 +睇 +伟 +觑 +羲 +嗜 +宜 +褐 +旎 +辛 +卦 +诘 +筋 +鎏 +溪 +挛 +熔 +阜 +晰 +鳅 +丢 +奚 +灸 +呱 +献 +陉 +黛 +鸪 +甾 +萨 +疮 +拯 +洲 +疹 +辑 +叙 +恻 +谒 +允 +柔 +烂 +氏 +逅 +漆 +拎 +惋 +扈 +湟 +纭 +啕 +掬 +擞 +哥 +忽 +涤 +鸵 +靡 +郗 +瓷 +扁 +廊 +怨 +雏 +钮 +敦 +E +懦 +憋 +汀 +拚 +啉 +腌 +岸 +f +痼 +瞅 +尊 +咀 +眩 +飙 +忌 +仝 +迦 +熬 +毫 +胯 +篑 +茄 +腺 +凄 +舛 +碴 +锵 +诧 +羯 +後 +漏 +汤 +宓 +仞 +蚁 +壶 +谰 +皑 +铄 +棰 +罔 +辅 +晶 +苦 +牟 +闽 +\ +烃 +饮 +聿 +丙 +蛳 +朱 +煤 +涔 +鳖 +犁 +罐 +荼 +砒 +淦 +妤 +黏 +戎 +孑 +婕 +瑾 +戢 +钵 +枣 +捋 +砥 +衩 +狙 +桠 +稣 +阎 +肃 +梏 +诫 +孪 +昶 +婊 +衫 +嗔 +侃 +塞 +蜃 +樵 +峒 +貌 +屿 +欺 +缫 +阐 +栖 +诟 +珞 +荭 +吝 +萍 +嗽 +恂 +啻 +蜴 +磬 +峋 +俸 +豫 +谎 +徊 +镍 +韬 +魇 +晴 +U +囟 +猜 +蛮 +坐 +囿 +伴 +亭 +肝 +佗 +蝠 +妃 +胞 +滩 +榴 +氖 +垩 +苋 +砣 +扪 +馏 +姓 +轩 +厉 +夥 +侈 +禀 +垒 +岑 +赏 +钛 +辐 +痔 +披 +纸 +碳 +“ +坞 +蠓 +挤 +荥 +沅 +悔 +铧 +帼 +蒌 +蝇 +a +p +y +n +g +哀 +浆 +瑶 +凿 +桶 +馈 +皮 +奴 +苜 +佤 +伶 +晗 +铱 +炬 +优 +弊 +氢 +恃 +甫 +攥 +端 +锌 +灰 +稹 +炝 +曙 +邋 +亥 +眶 +碾 +拉 +萝 +绔 +捷 +浍 +腋 +姑 +菖 +凌 +涞 +麽 +锢 +桨 +潢 +绎 +镰 +殆 +锑 +渝 +铬 +困 +绽 +觎 +匈 +糙 +暑 +裹 +鸟 +盔 +肽 +迷 +綦 +『 +亳 +佝 +俘 +钴 +觇 +骥 +仆 +疝 +跪 +婶 +郯 +瀹 +唉 +脖 +踞 +针 +晾 +忒 +扼 +瞩 +叛 +椒 +疟 +嗡 +邗 +肆 +跆 +玫 +忡 +捣 +咧 +唆 +艄 +蘑 +潦 +笛 +阚 +沸 +泻 +掊 +菽 +贫 +斥 +髂 +孢 +镂 +赂 +麝 +鸾 +屡 +衬 +苷 +恪 +叠 +希 +粤 +爻 +喝 +茫 +惬 +郸 +绻 +庸 +撅 +碟 +宄 +妹 +膛 +叮 +饵 +崛 +嗲 +椅 +冤 +搅 +咕 +敛 +尹 +垦 +闷 +蝉 +霎 +勰 +败 +蓑 +泸 +肤 +鹌 +幌 +焦 +浠 +鞍 +刁 +舰 +乙 +竿 +裔 +。 +茵 +函 +伊 +兄 +丨 +娜 +匍 +謇 +莪 +宥 +似 +蝽 +翳 +酪 +翠 +粑 +薇 +祢 +骏 +赠 +叫 +Q +噤 +噻 +竖 +芗 +莠 +潭 +俊 +羿 +耜 +O +郫 +趁 +嗪 +囚 +蹶 +芒 +洁 +笋 +鹑 +敲 +硝 +啶 +堡 +渲 +揩 +』 +携 +宿 +遒 +颍 +扭 +棱 +割 +萜 +蔸 +葵 +琴 +捂 +饰 +衙 +耿 +掠 +募 +岂 +窖 +涟 +蔺 +瘤 +柞 +瞪 +怜 +匹 +距 +楔 +炜 +哆 +秦 +缎 +幼 +茁 +绪 +痨 +恨 +楸 +娅 +瓦 +桩 +雪 +嬴 +伏 +榔 +妥 +铿 +拌 +眠 +雍 +缇 +‘ +卓 +搓 +哌 +觞 +噩 +屈 +哧 +髓 +咦 +巅 +娑 +侑 +淫 +膳 +祝 +勾 +姊 +莴 +胄 +疃 +薛 +蜷 +胛 +巷 +芙 +芋 +熙 +闰 +勿 +窃 +狱 +剩 +钏 +幢 +陟 +铛 +慧 +靴 +耍 +k +浙 +浇 +飨 +惟 +绗 +祜 +澈 +啼 +咪 +磷 +摞 +诅 +郦 +抹 +跃 +壬 +吕 +肖 +琏 +颤 +尴 +剡 +抠 +凋 +赚 +泊 +津 +宕 +殷 +倔 +氲 +漫 +邺 +涎 +怠 +$ +垮 +荬 +遵 +俏 +叹 +噢 +饽 +蜘 +孙 +筵 +疼 +鞭 +羧 +牦 +箭 +潴 +c +眸 +祭 +髯 +啖 +坳 +愁 +芩 +驮 +倡 +巽 +穰 +沃 +胚 +怒 +凤 +槛 +剂 +趵 +嫁 +v +邢 +灯 +鄢 +桐 +睽 +檗 +锯 +槟 +婷 +嵋 +圻 +诗 +蕈 +颠 +遭 +痢 +芸 +怯 +馥 +竭 +锗 +徜 +恭 +遍 +籁 +剑 +嘱 +苡 +龄 +僧 +桑 +潸 +弘 +澶 +楹 +悲 +讫 +愤 +腥 +悸 +谍 +椹 +呢 +桓 +葭 +攫 +阀 +翰 +躲 +敖 +柑 +郎 +笨 +橇 +呃 +魁 +燎 +脓 +葩 +磋 +垛 +玺 +狮 +沓 +砜 +蕊 +锺 +罹 +蕉 +翱 +虐 +闾 +巫 +旦 +茱 +嬷 +枯 +鹏 +贡 +芹 +汛 +矫 +绁 +拣 +禺 +佃 +讣 +舫 +惯 +乳 +趋 +疲 +挽 +岚 +虾 +衾 +蠹 +蹂 +飓 +氦 +铖 +孩 +稞 +瑜 +壅 +掀 +勘 +妓 +畅 +髋 +W +庐 +牲 +蓿 +榕 +练 +垣 +唱 +邸 +菲 +昆 +婺 +穿 +绡 +麒 +蚱 +掂 +愚 +泷 +涪 +漳 +妩 +娉 +榄 +讷 +觅 +旧 +藤 +煮 +呛 +柳 +腓 +叭 +庵 +烷 +阡 +罂 +蜕 +擂 +猖 +咿 +媲 +脉 +【 +沏 +貅 +黠 +熏 +哲 +烁 +坦 +酵 +兜 +× +潇 +撒 +剽 +珩 +圹 +乾 +摸 +樟 +帽 +嗒 +襄 +魂 +轿 +憬 +锡 +〕 +喃 +皆 +咖 +隅 +脸 +残 +泮 +袂 +鹂 +珊 +囤 +捆 +咤 +误 +徨 +闹 +淙 +芊 +淋 +怆 +囗 +拨 +梳 +渤 +R +G +绨 +蚓 +婀 +幡 +狩 +麾 +谢 +唢 +裸 +旌 +伉 +纶 +裂 +驳 +砼 +咛 +澄 +樨 +蹈 +宙 +澍 +倍 +貔 +操 +勇 +蟠 +摈 +砧 +虬 +够 +缁 +悦 +藿 +撸 +艹 +摁 +淹 +豇 +虎 +榭 +ˉ +吱 +d +° +喧 +荀 +踱 +侮 +奋 +偕 +饷 +犍 +惮 +坑 +璎 +徘 +宛 +妆 +袈 +倩 +窦 +昂 +荏 +乖 +K +怅 +撰 +鳙 +牙 +袁 +酞 +X +痿 +琼 +闸 +雁 +趾 +荚 +虻 +涝 +《 +杏 +韭 +偈 +烤 +绫 +鞘 +卉 +症 +遢 +蓥 +诋 +杭 +荨 +匆 +竣 +簪 +辙 +敕 +虞 +丹 +缭 +咩 +黟 +m +淤 +瑕 +咂 +铉 +硼 +茨 +嶂 +痒 +畸 +敬 +涿 +粪 +窘 +熟 +叔 +嫔 +盾 +忱 +裘 +憾 +梵 +赡 +珙 +咯 +娘 +庙 +溯 +胺 +葱 +痪 +摊 +荷 +卞 +乒 +髦 +寐 +铭 +坩 +胗 +枷 +爆 +溟 +嚼 +羚 +砬 +轨 +惊 +挠 +罄 +竽 +菏 +氧 +浅 +楣 +盼 +枢 +炸 +阆 +杯 +谏 +噬 +淇 +渺 +俪 +秆 +墓 +泪 +跻 +砌 +痰 +垡 +渡 +耽 +釜 +讶 +鳎 +煞 +呗 +韶 +舶 +绷 +鹳 +缜 +旷 +铊 +皱 +龌 +檀 +霖 +奄 +槐 +艳 +蝶 +旋 +哝 +赶 +骞 +蚧 +腊 +盈 +丁 +` +蜚 +矸 +蝙 +睨 +嚓 +僻 +鬼 +醴 +夜 +彝 +磊 +笔 +拔 +栀 +糕 +厦 +邰 +纫 +逭 +纤 +眦 +膊 +馍 +躇 +烯 +蘼 +冬 +诤 +暄 +骶 +哑 +瘠 +」 +臊 +丕 +愈 +咱 +螺 +擅 +跋 +搏 +硪 +谄 +笠 +淡 +嘿 +骅 +谧 +鼎 +皋 +姚 +歼 +蠢 +驼 +耳 +胬 +挝 +涯 +狗 +蒽 +孓 +犷 +凉 +芦 +箴 +铤 +孤 +嘛 +坤 +V +茴 +朦 +挞 +尖 +橙 +诞 +搴 +碇 +洵 +浚 +帚 +蜍 +漯 +柘 +嚎 +讽 +芭 +荤 +咻 +祠 +秉 +跖 +埃 +吓 +糯 +眷 +馒 +惹 +娼 +鲑 +嫩 +讴 +轮 +瞥 +靶 +褚 +乏 +缤 +宋 +帧 +删 +驱 +碎 +扑 +俩 +俄 +偏 +涣 +竹 +噱 +皙 +佰 +渚 +唧 +斡 +# +镉 +刀 +崎 +筐 +佣 +夭 +贰 +肴 +峙 +哔 +艿 +匐 +牺 +镛 +缘 +仡 +嫡 +劣 +枸 +堀 +梨 +簿 +鸭 +蒸 +亦 +稽 +浴 +{ +衢 +束 +槲 +j +阁 +揍 +疥 +棋 +潋 +聪 +窜 +乓 +睛 +插 +冉 +阪 +苍 +搽 +「 +蟾 +螟 +幸 +仇 +樽 +撂 +慢 +跤 +幔 +俚 +淅 +覃 +觊 +溶 +妖 +帛 +侨 +曰 +妾 +泗 +· +: +瀘 +風 +Ë +( +) +∶ +紅 +紗 +瑭 +雲 +頭 +鶏 +財 +許 +• +¥ +樂 +焗 +麗 +— +; +滙 +東 +榮 +繪 +興 +… +門 +業 +π +楊 +國 +顧 +é +盤 +寳 +Λ +龍 +鳳 +島 +誌 +緣 +結 +銭 +萬 +勝 +祎 +璟 +優 +歡 +臨 +時 +購 += +★ +藍 +昇 +鐵 +觀 +勅 +農 +聲 +畫 +兿 +術 +發 +劉 +記 +專 +耑 +園 +書 +壴 +種 +Ο +● +褀 +號 +銀 +匯 +敟 +锘 +葉 +橪 +廣 +進 +蒄 +鑽 +阝 +祙 +貢 +鍋 +豊 +夬 +喆 +團 +閣 +開 +燁 +賓 +館 +酡 +沔 +順 ++ +硚 +劵 +饸 +陽 +車 +湓 +復 +萊 +氣 +軒 +華 +堃 +迮 +纟 +戶 +馬 +學 +裡 +電 +嶽 +獨 +マ +シ +サ +ジ +燘 +袪 +環 +❤ +臺 +灣 +専 +賣 +孖 +聖 +攝 +線 +▪ +α +傢 +俬 +夢 +達 +莊 +喬 +貝 +薩 +劍 +羅 +壓 +棛 +饦 +尃 +璈 +囍 +醫 +G +I +A +# +N +鷄 +髙 +嬰 +啓 +約 +隹 +潔 +賴 +藝 +~ +寶 +籣 +麺 +  +嶺 +√ +義 +網 +峩 +長 +∧ +魚 +機 +構 +② +鳯 +偉 +L +B +㙟 +畵 +鴿 +' +詩 +溝 +嚞 +屌 +藔 +佧 +玥 +蘭 +織 +1 +3 +9 +0 +7 +點 +砭 +鴨 +鋪 +銘 +廳 +弍 +‧ +創 +湯 +坶 +℃ +卩 +骝 +& +烜 +荘 +當 +潤 +扞 +係 +懷 +碶 +钅 +蚨 +讠 +☆ +叢 +爲 +埗 +涫 +塗 +→ +楽 +現 +鯨 +愛 +瑪 +鈺 +忄 +悶 +藥 +飾 +樓 +視 +孬 +ㆍ +燚 +苪 +師 +① +丼 +锽 +│ +韓 +標 +è +兒 +閏 +匋 +張 +漢 +Ü +髪 +會 +閑 +檔 +習 +裝 +の +峯 +菘 +輝 +И +雞 +釣 +億 +浐 +K +O +R +8 +H +E +P +T +W +D +S +C +M +F +姌 +饹 +» +晞 +廰 +ä +嵯 +鷹 +負 +飲 +絲 +冚 +楗 +澤 +綫 +區 +❋ +← +質 +靑 +揚 +③ +滬 +統 +産 +協 +﹑ +乸 +畐 +經 +運 +際 +洺 +岽 +為 +粵 +諾 +崋 +豐 +碁 +ɔ +V +2 +6 +齋 +誠 +訂 +´ +勑 +雙 +陳 +無 +í +泩 +媄 +夌 +刂 +i +c +t +o +r +a +嘢 +耄 +燴 +暃 +壽 +媽 +靈 +抻 +體 +唻 +É +冮 +甹 +鎮 +錦 +ʌ +蜛 +蠄 +尓 +駕 +戀 +飬 +逹 +倫 +貴 +極 +Я +Й +寬 +磚 +嶪 +郎 +職 +| +間 +n +d +剎 +伈 +課 +飛 +橋 +瘊 +№ +譜 +骓 +圗 +滘 +縣 +粿 +咅 +養 +濤 +彳 +® +% +Ⅱ +啰 +㴪 +見 +矞 +薬 +糁 +邨 +鲮 +顔 +罱 +З +選 +話 +贏 +氪 +俵 +競 +瑩 +繡 +枱 +β +綉 +á +獅 +爾 +™ +麵 +戋 +淩 +徳 +個 +劇 +場 +務 +簡 +寵 +h +實 +膠 +轱 +圖 +築 +嘣 +樹 +㸃 +營 +耵 +孫 +饃 +鄺 +飯 +麯 +遠 +輸 +坫 +孃 +乚 +閃 +鏢 +㎡ +題 +廠 +關 +↑ +爺 +將 +軍 +連 +篦 +覌 +參 +箸 +- +窠 +棽 +寕 +夀 +爰 +歐 +呙 +閥 +頡 +熱 +雎 +垟 +裟 +凬 +勁 +帑 +馕 +夆 +疌 +枼 +馮 +貨 +蒤 +樸 +彧 +旸 +靜 +龢 +暢 +㐱 +鳥 +珺 +鏡 +灡 +爭 +堷 +廚 +Ó +騰 +診 +┅ +蘇 +褔 +凱 +頂 +豕 +亞 +帥 +嘬 +⊥ +仺 +桖 +複 +饣 +絡 +穂 +顏 +棟 +納 +▏ +濟 +親 +設 +計 +攵 +埌 +烺 +ò +頤 +燦 +蓮 +撻 +節 +講 +濱 +濃 +娽 +洳 +朿 +燈 +鈴 +護 +膚 +铔 +過 +補 +Z +U +5 +4 +坋 +闿 +䖝 +餘 +缐 +铞 +貿 +铪 +桼 +趙 +鍊 +[ +㐂 +垚 +菓 +揸 +捲 +鐘 +滏 +𣇉 +爍 +輪 +燜 +鴻 +鮮 +動 +鹞 +鷗 +丄 +慶 +鉌 +翥 +飮 +腸 +⇋ +漁 +覺 +來 +熘 +昴 +翏 +鲱 +圧 +鄉 +萭 +頔 +爐 +嫚 +г +貭 +類 +聯 +幛 +輕 +訓 +鑒 +夋 +锨 +芃 +珣 +䝉 +扙 +嵐 +銷 +處 +ㄱ +語 +誘 +苝 +歸 +儀 +燒 +楿 +內 +粢 +葒 +奧 +麥 +礻 +滿 +蠔 +穵 +瞭 +態 +鱬 +榞 +硂 +鄭 +黃 +煙 +祐 +奓 +逺 +* +瑄 +獲 +聞 +薦 +讀 +這 +樣 +決 +問 +啟 +們 +執 +説 +轉 +單 +隨 +唘 +帶 +倉 +庫 +還 +贈 +尙 +皺 +■ +餅 +產 +○ +∈ +報 +狀 +楓 +賠 +琯 +嗮 +禮 +` +傳 +> +≤ +嗞 +Φ +≥ +換 +咭 +∣ +↓ +曬 +ε +応 +寫 +″ +終 +様 +純 +費 +療 +聨 +凍 +壐 +郵 +ü +黒 +∫ +製 +塊 +調 +軽 +確 +撃 +級 +馴 +Ⅲ +涇 +繹 +數 +碼 +證 +狒 +処 +劑 +< +晧 +賀 +衆 +] +櫥 +兩 +陰 +絶 +對 +鯉 +憶 +◎ +p +e +Y +蕒 +煖 +頓 +測 +試 +鼽 +僑 +碩 +妝 +帯 +≈ +鐡 +舖 +權 +喫 +倆 +ˋ +該 +悅 +ā +俫 +. +f +s +b +m +k +g +u +j +貼 +淨 +濕 +針 +適 +備 +l +/ +給 +謢 +強 +觸 +衛 +與 +⊙ +$ +緯 +變 +⑴ +⑵ +⑶ +㎏ +殺 +∩ +幚 +─ +價 +▲ +離 +ú +ó +飄 +烏 +関 +閟 +﹝ +﹞ +邏 +輯 +鍵 +驗 +訣 +導 +歷 +屆 +層 +▼ +儱 +錄 +熳 +ē +艦 +吋 +錶 +辧 +飼 +顯 +④ +禦 +販 +気 +対 +枰 +閩 +紀 +幹 +瞓 +貊 +淚 +△ +眞 +墊 +Ω +獻 +褲 +縫 +緑 +亜 +鉅 +餠 +{ +} +◆ +蘆 +薈 +█ +◇ +溫 +彈 +晳 +粧 +犸 +穩 +訊 +崬 +凖 +熥 +П +舊 +條 +紋 +圍 +Ⅳ +筆 +尷 +難 +雜 +錯 +綁 +識 +頰 +鎖 +艶 +□ +殁 +殼 +⑧ +├ +▕ +鵬 +ǐ +ō +ǒ +糝 +綱 +▎ +μ +盜 +饅 +醬 +籤 +蓋 +釀 +鹽 +據 +à +ɡ +辦 +◥ +彐 +┌ +婦 +獸 +鲩 +伱 +ī +蒟 +蒻 +齊 +袆 +腦 +寧 +凈 +妳 +煥 +詢 +偽 +謹 +啫 +鯽 +騷 +鱸 +損 +傷 +鎻 +髮 +買 +冏 +儥 +両 +﹢ +∞ +載 +喰 +z +羙 +悵 +燙 +曉 +員 +組 +徹 +艷 +痠 +鋼 +鼙 +縮 +細 +嚒 +爯 +≠ +維 +" +鱻 +壇 +厍 +帰 +浥 +犇 +薡 +軎 +² +應 +醜 +刪 +緻 +鶴 +賜 +噁 +軌 +尨 +镔 +鷺 +槗 +彌 +葚 +濛 +請 +溇 +緹 +賢 +訪 +獴 +瑅 +資 +縤 +陣 +蕟 +栢 +韻 +祼 +恁 +伢 +謝 +劃 +涑 +總 +衖 +踺 +砋 +凉 +籃 +駿 +苼 +瘋 +昽 +紡 +驊 +腎 +﹗ +響 +杋 +剛 +嚴 +禪 +歓 +槍 +傘 +檸 +檫 +炣 +勢 +鏜 +鎢 +銑 +尐 +減 +奪 +惡 +θ +僮 +婭 +臘 +ū +ì +殻 +鉄 +∑ +蛲 +焼 +緖 +續 +紹 +懮 \ No newline at end of file diff --git a/py/iopaint/model/anytext/utils.py b/py/iopaint/model/anytext/utils.py new file mode 100644 index 0000000..c9f55b8 --- /dev/null +++ b/py/iopaint/model/anytext/utils.py @@ -0,0 +1,151 @@ +import os +import datetime +import cv2 +import numpy as np +from PIL import Image, ImageDraw + + +def save_images(img_list, folder): + if not os.path.exists(folder): + os.makedirs(folder) + now = datetime.datetime.now() + date_str = now.strftime("%Y-%m-%d") + folder_path = os.path.join(folder, date_str) + if not os.path.exists(folder_path): + os.makedirs(folder_path) + time_str = now.strftime("%H_%M_%S") + for idx, img in enumerate(img_list): + image_number = idx + 1 + filename = f"{time_str}_{image_number}.jpg" + save_path = os.path.join(folder_path, filename) + cv2.imwrite(save_path, img[..., ::-1]) + + +def check_channels(image): + channels = image.shape[2] if len(image.shape) == 3 else 1 + if channels == 1: + image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR) + elif channels > 3: + image = image[:, :, :3] + return image + + +def resize_image(img, max_length=768): + height, width = img.shape[:2] + max_dimension = max(height, width) + + if max_dimension > max_length: + scale_factor = max_length / max_dimension + new_width = int(round(width * scale_factor)) + new_height = int(round(height * scale_factor)) + new_size = (new_width, new_height) + img = cv2.resize(img, new_size) + height, width = img.shape[:2] + img = cv2.resize(img, (width - (width % 64), height - (height % 64))) + return img + + +def insert_spaces(string, nSpace): + if nSpace == 0: + return string + new_string = "" + for char in string: + new_string += char + " " * nSpace + return new_string[:-nSpace] + + +def draw_glyph(font, text): + g_size = 50 + W, H = (512, 80) + new_font = font.font_variant(size=g_size) + img = Image.new(mode="1", size=(W, H), color=0) + draw = ImageDraw.Draw(img) + left, top, right, bottom = new_font.getbbox(text) + text_width = max(right - left, 5) + text_height = max(bottom - top, 5) + ratio = min(W * 0.9 / text_width, H * 0.9 / text_height) + new_font = font.font_variant(size=int(g_size * ratio)) + + text_width, text_height = new_font.getsize(text) + offset_x, offset_y = new_font.getoffset(text) + x = (img.width - text_width) // 2 + y = (img.height - text_height) // 2 - offset_y // 2 + draw.text((x, y), text, font=new_font, fill="white") + img = np.expand_dims(np.array(img), axis=2).astype(np.float64) + return img + + +def draw_glyph2( + font, text, polygon, vertAng=10, scale=1, width=512, height=512, add_space=True +): + enlarge_polygon = polygon * scale + rect = cv2.minAreaRect(enlarge_polygon) + box = cv2.boxPoints(rect) + box = np.int0(box) + w, h = rect[1] + angle = rect[2] + if angle < -45: + angle += 90 + angle = -angle + if w < h: + angle += 90 + + vert = False + if abs(angle) % 90 < vertAng or abs(90 - abs(angle) % 90) % 90 < vertAng: + _w = max(box[:, 0]) - min(box[:, 0]) + _h = max(box[:, 1]) - min(box[:, 1]) + if _h >= _w: + vert = True + angle = 0 + + img = np.zeros((height * scale, width * scale, 3), np.uint8) + img = Image.fromarray(img) + + # infer font size + image4ratio = Image.new("RGB", img.size, "white") + draw = ImageDraw.Draw(image4ratio) + _, _, _tw, _th = draw.textbbox(xy=(0, 0), text=text, font=font) + text_w = min(w, h) * (_tw / _th) + if text_w <= max(w, h): + # add space + if len(text) > 1 and not vert and add_space: + for i in range(1, 100): + text_space = insert_spaces(text, i) + _, _, _tw2, _th2 = draw.textbbox(xy=(0, 0), text=text_space, font=font) + if min(w, h) * (_tw2 / _th2) > max(w, h): + break + text = insert_spaces(text, i - 1) + font_size = min(w, h) * 0.80 + else: + shrink = 0.75 if vert else 0.85 + font_size = min(w, h) / (text_w / max(w, h)) * shrink + new_font = font.font_variant(size=int(font_size)) + + left, top, right, bottom = new_font.getbbox(text) + text_width = right - left + text_height = bottom - top + + layer = Image.new("RGBA", img.size, (0, 0, 0, 0)) + draw = ImageDraw.Draw(layer) + if not vert: + draw.text( + (rect[0][0] - text_width // 2, rect[0][1] - text_height // 2 - top), + text, + font=new_font, + fill=(255, 255, 255, 255), + ) + else: + x_s = min(box[:, 0]) + _w // 2 - text_height // 2 + y_s = min(box[:, 1]) + for c in text: + draw.text((x_s, y_s), c, font=new_font, fill=(255, 255, 255, 255)) + _, _t, _, _b = new_font.getbbox(c) + y_s += _b + + rotated_layer = layer.rotate(angle, expand=1, center=(rect[0][0], rect[0][1])) + + x_offset = int((img.width - rotated_layer.width) / 2) + y_offset = int((img.height - rotated_layer.height) / 2) + img.paste(rotated_layer, (x_offset, y_offset), rotated_layer) + img = np.expand_dims(np.array(img.convert("1")), axis=2).astype(np.float64) + return img diff --git a/py/iopaint/model/base.py b/py/iopaint/model/base.py new file mode 100644 index 0000000..e992e00 --- /dev/null +++ b/py/iopaint/model/base.py @@ -0,0 +1,418 @@ +import abc +from typing import Optional + +import cv2 +import torch +import numpy as np +from loguru import logger + +from ..helper import ( + boxes_from_mask, + resize_max_size, + pad_img_to_modulo, + switch_mps_device, +) +from ..schema import InpaintRequest, HDStrategy, SDSampler +from .helper.g_diffuser_bot import expand_image +from .utils import get_scheduler + + +class InpaintModel: + name = "base" + min_size: Optional[int] = None + pad_mod = 8 + pad_to_square = False + is_erase_model = False + + def __init__(self, device, **kwargs): + """ + + Args: + device: + """ + device = switch_mps_device(self.name, device) + self.device = device + self.init_model(device, **kwargs) + + @abc.abstractmethod + def init_model(self, device, **kwargs): + ... + + @staticmethod + @abc.abstractmethod + def is_downloaded() -> bool: + return False + + @abc.abstractmethod + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W, 1] 255 为 masks 区域 + return: BGR IMAGE + """ + ... + + @staticmethod + def download(): + ... + + def _pad_forward(self, image, mask, config: InpaintRequest): + origin_height, origin_width = image.shape[:2] + pad_image = pad_img_to_modulo( + image, mod=self.pad_mod, square=self.pad_to_square, min_size=self.min_size + ) + pad_mask = pad_img_to_modulo( + mask, mod=self.pad_mod, square=self.pad_to_square, min_size=self.min_size + ) + + # logger.info(f"final forward pad size: {pad_image.shape}") + + image, mask = self.forward_pre_process(image, mask, config) + + result = self.forward(pad_image, pad_mask, config) + result = result[0:origin_height, 0:origin_width, :] + + result, image, mask = self.forward_post_process(result, image, mask, config) + + if config.sd_keep_unmasked_area: + mask = mask[:, :, np.newaxis] + result = result * (mask / 255) + image[:, :, ::-1] * (1 - (mask / 255)) + return result + + def forward_pre_process(self, image, mask, config): + return image, mask + + def forward_post_process(self, result, image, mask, config): + return result, image, mask + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + inpaint_result = None + # logger.info(f"hd_strategy: {config.hd_strategy}") + if config.hd_strategy == HDStrategy.CROP: + if max(image.shape) > config.hd_strategy_crop_trigger_size: + logger.info(f"Run crop strategy") + boxes = boxes_from_mask(mask) + crop_result = [] + for box in boxes: + crop_image, crop_box = self._run_box(image, mask, box, config) + crop_result.append((crop_image, crop_box)) + + inpaint_result = image[:, :, ::-1] + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + elif config.hd_strategy == HDStrategy.RESIZE: + if max(image.shape) > config.hd_strategy_resize_limit: + origin_size = image.shape[:2] + downsize_image = resize_max_size( + image, size_limit=config.hd_strategy_resize_limit + ) + downsize_mask = resize_max_size( + mask, size_limit=config.hd_strategy_resize_limit + ) + + logger.info( + f"Run resize strategy, origin size: {image.shape} forward size: {downsize_image.shape}" + ) + inpaint_result = self._pad_forward( + downsize_image, downsize_mask, config + ) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + original_pixel_indices = mask < 127 + inpaint_result[original_pixel_indices] = image[:, :, ::-1][ + original_pixel_indices + ] + + if inpaint_result is None: + inpaint_result = self._pad_forward(image, mask, config) + + return inpaint_result + + def _crop_box(self, image, mask, box, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] + box: [left,top,right,bottom] + + Returns: + BGR IMAGE, (l, r, r, b) + """ + box_h = box[3] - box[1] + box_w = box[2] - box[0] + cx = (box[0] + box[2]) // 2 + cy = (box[1] + box[3]) // 2 + img_h, img_w = image.shape[:2] + + w = box_w + config.hd_strategy_crop_margin * 2 + h = box_h + config.hd_strategy_crop_margin * 2 + + _l = cx - w // 2 + _r = cx + w // 2 + _t = cy - h // 2 + _b = cy + h // 2 + + l = max(_l, 0) + r = min(_r, img_w) + t = max(_t, 0) + b = min(_b, img_h) + + # try to get more context when crop around image edge + if _l < 0: + r += abs(_l) + if _r > img_w: + l -= _r - img_w + if _t < 0: + b += abs(_t) + if _b > img_h: + t -= _b - img_h + + l = max(l, 0) + r = min(r, img_w) + t = max(t, 0) + b = min(b, img_h) + + crop_img = image[t:b, l:r, :] + crop_mask = mask[t:b, l:r] + + # logger.info(f"box size: ({box_h},{box_w}) crop size: {crop_img.shape}") + + return crop_img, crop_mask, [l, t, r, b] + + def _calculate_cdf(self, histogram): + cdf = histogram.cumsum() + normalized_cdf = cdf / float(cdf.max()) + return normalized_cdf + + def _calculate_lookup(self, source_cdf, reference_cdf): + lookup_table = np.zeros(256) + lookup_val = 0 + for source_index, source_val in enumerate(source_cdf): + for reference_index, reference_val in enumerate(reference_cdf): + if reference_val >= source_val: + lookup_val = reference_index + break + lookup_table[source_index] = lookup_val + return lookup_table + + def _match_histograms(self, source, reference, mask): + transformed_channels = [] + if len(mask.shape) == 3: + mask = mask[:, :, -1] + + for channel in range(source.shape[-1]): + source_channel = source[:, :, channel] + reference_channel = reference[:, :, channel] + + # only calculate histograms for non-masked parts + source_histogram, _ = np.histogram(source_channel[mask == 0], 256, [0, 256]) + reference_histogram, _ = np.histogram( + reference_channel[mask == 0], 256, [0, 256] + ) + + source_cdf = self._calculate_cdf(source_histogram) + reference_cdf = self._calculate_cdf(reference_histogram) + + lookup = self._calculate_lookup(source_cdf, reference_cdf) + + transformed_channels.append(cv2.LUT(source_channel, lookup)) + + result = cv2.merge(transformed_channels) + result = cv2.convertScaleAbs(result) + + return result + + def _apply_cropper(self, image, mask, config: InpaintRequest): + img_h, img_w = image.shape[:2] + l, t, w, h = ( + config.croper_x, + config.croper_y, + config.croper_width, + config.croper_height, + ) + r = l + w + b = t + h + + l = max(l, 0) + r = min(r, img_w) + t = max(t, 0) + b = min(b, img_h) + + crop_img = image[t:b, l:r, :] + crop_mask = mask[t:b, l:r] + return crop_img, crop_mask, (l, t, r, b) + + def _run_box(self, image, mask, box, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] + box: [left,top,right,bottom] + + Returns: + BGR IMAGE + """ + crop_img, crop_mask, [l, t, r, b] = self._crop_box(image, mask, box, config) + + return self._pad_forward(crop_img, crop_mask, config), [l, t, r, b] + + +class DiffusionInpaintModel(InpaintModel): + def __init__(self, device, **kwargs): + self.model_info = kwargs["model_info"] + self.model_id_or_path = self.model_info.path + super().__init__(device, **kwargs) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + # boxes = boxes_from_mask(mask) + if config.use_croper: + crop_img, crop_mask, (l, t, r, b) = self._apply_cropper(image, mask, config) + crop_image = self._scaled_pad_forward(crop_img, crop_mask, config) + inpaint_result = image[:, :, ::-1] + inpaint_result[t:b, l:r, :] = crop_image + elif config.use_extender: + inpaint_result = self._do_outpainting(image, config) + else: + inpaint_result = self._scaled_pad_forward(image, mask, config) + + return inpaint_result + + def _do_outpainting(self, image, config: InpaintRequest): + # cropper 和 image 在同一个坐标系下,croper_x/y 可能为负数 + # 从 image 中 crop 出 outpainting 区域 + image_h, image_w = image.shape[:2] + cropper_l = config.extender_x + cropper_t = config.extender_y + cropper_r = config.extender_x + config.extender_width + cropper_b = config.extender_y + config.extender_height + image_l = 0 + image_t = 0 + image_r = image_w + image_b = image_h + + # 类似求 IOU + l = max(cropper_l, image_l) + t = max(cropper_t, image_t) + r = min(cropper_r, image_r) + b = min(cropper_b, image_b) + + assert ( + 0 <= l < r and 0 <= t < b + ), f"cropper and image not overlap, {l},{t},{r},{b}" + + cropped_image = image[t:b, l:r, :] + padding_l = max(0, image_l - cropper_l) + padding_t = max(0, image_t - cropper_t) + padding_r = max(0, cropper_r - image_r) + padding_b = max(0, cropper_b - image_b) + + expanded_image, mask_image = expand_image( + cropped_image, + left=padding_l, + top=padding_t, + right=padding_r, + bottom=padding_b, + softness=config.sd_outpainting_softness, + space=config.sd_outpainting_space, + ) + + # 最终扩大了的 image, BGR + expanded_cropped_result_image = self._scaled_pad_forward( + expanded_image, mask_image, config + ) + + # RGB -> BGR + outpainting_image = cv2.copyMakeBorder( + image, + left=padding_l, + top=padding_t, + right=padding_r, + bottom=padding_b, + borderType=cv2.BORDER_CONSTANT, + value=0, + )[:, :, ::-1] + + # 把 cropped_result_image 贴到 outpainting_image 上,这一步不需要 blend + paste_t = 0 if config.extender_y < 0 else config.extender_y + paste_l = 0 if config.extender_x < 0 else config.extender_x + + outpainting_image[ + paste_t : paste_t + expanded_cropped_result_image.shape[0], + paste_l : paste_l + expanded_cropped_result_image.shape[1], + :, + ] = expanded_cropped_result_image + return outpainting_image + + def _scaled_pad_forward(self, image, mask, config: InpaintRequest): + longer_side_length = int(config.sd_scale * max(image.shape[:2])) + origin_size = image.shape[:2] + downsize_image = resize_max_size(image, size_limit=longer_side_length) + downsize_mask = resize_max_size(mask, size_limit=longer_side_length) + if config.sd_scale != 1: + logger.info( + f"Resize image to do sd inpainting: {image.shape} -> {downsize_image.shape}" + ) + inpaint_result = self._pad_forward(downsize_image, downsize_mask, config) + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + # blend result, copy from g_diffuser_bot + # mask_rgb = 1.0 - np_img_grey_to_rgb(mask / 255.0) + # inpaint_result = np.clip( + # inpaint_result * (1.0 - mask_rgb) + image * mask_rgb, 0.0, 255.0 + # ) + # original_pixel_indices = mask < 127 + # inpaint_result[original_pixel_indices] = image[:, :, ::-1][ + # original_pixel_indices + # ] + return inpaint_result + + def set_scheduler(self, config: InpaintRequest): + scheduler_config = self.model.scheduler.config + sd_sampler = config.sd_sampler + if config.sd_lcm_lora and self.model_info.support_lcm_lora: + sd_sampler = SDSampler.lcm + logger.info(f"LCM Lora enabled, use {sd_sampler} sampler") + scheduler = get_scheduler(sd_sampler, scheduler_config) + self.model.scheduler = scheduler + + def forward_pre_process(self, image, mask, config): + if config.sd_mask_blur != 0: + k = 2 * config.sd_mask_blur + 1 + mask = cv2.GaussianBlur(mask, (k, k), 0) + + return image, mask + + def forward_post_process(self, result, image, mask, config): + if config.sd_match_histograms: + result = self._match_histograms(result, image[:, :, ::-1], mask) + + # if config.sd_mask_blur != 0: + # k = 2 * config.sd_mask_blur + 1 + # mask = cv2.GaussianBlur(mask, (k, k), 0) + return result, image, mask diff --git a/py/iopaint/model/controlnet.py b/py/iopaint/model/controlnet.py new file mode 100644 index 0000000..74453ad --- /dev/null +++ b/py/iopaint/model/controlnet.py @@ -0,0 +1,190 @@ +import PIL.Image +import cv2 +import torch +from diffusers import ControlNetModel +from loguru import logger +from ..schema import InpaintRequest, ModelType + +from .base import DiffusionInpaintModel +from .helper.controlnet_preprocess import ( + make_canny_control_image, + make_openpose_control_image, + make_depth_control_image, + make_inpaint_control_image, +) +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + get_scheduler, + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) + + +class ControlNet(DiffusionInpaintModel): + name = "controlnet" + pad_mod = 8 + min_size = 512 + + @property + def lcm_lora_id(self): + if self.model_info.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SD_INPAINT, + ]: + return "latent-consistency/lcm-lora-sdv1-5" + if self.model_info.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return "latent-consistency/lcm-lora-sdxl" + raise NotImplementedError(f"Unsupported controlnet lcm model {self.model_info}") + + def init_model(self, device: torch.device, **kwargs): + model_info = kwargs["model_info"] + controlnet_method = kwargs["controlnet_method"] + + self.model_info = model_info + self.controlnet_method = controlnet_method + + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + self.local_files_only = model_kwargs["local_files_only"] + + disable_nsfw_checker = kwargs["disable_nsfw"] or kwargs.get( + "cpu_offload", False + ) + if disable_nsfw_checker: + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + self.torch_dtype = torch_dtype + + if model_info.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SD_INPAINT, + ]: + from diffusers import ( + StableDiffusionControlNetInpaintPipeline as PipeClass, + ) + elif model_info.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + from diffusers import ( + StableDiffusionXLControlNetInpaintPipeline as PipeClass, + ) + + controlnet = ControlNetModel.from_pretrained( + pretrained_model_name_or_path=controlnet_method, + resume_download=True, + local_files_only=model_kwargs["local_files_only"], + torch_dtype=self.torch_dtype, + ) + if model_info.is_single_file_diffusers: + if self.model_info.model_type == ModelType.DIFFUSERS_SD: + model_kwargs["num_in_channels"] = 4 + else: + model_kwargs["num_in_channels"] = 9 + + self.model = PipeClass.from_single_file( + model_info.path, + controlnet=controlnet, + load_safety_checker=not disable_nsfw_checker, + torch_dtype=torch_dtype, + config_files=get_config_files(), + **model_kwargs, + ) + else: + self.model = handle_from_pretrained_exceptions( + PipeClass.from_pretrained, + pretrained_model_name_or_path=model_info.path, + controlnet=controlnet, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def switch_controlnet_method(self, new_method: str): + self.controlnet_method = new_method + controlnet = ControlNetModel.from_pretrained( + new_method, + resume_download=True, + local_files_only=self.local_files_only, + torch_dtype=self.torch_dtype, + ).to(self.model.device) + self.model.controlnet = controlnet + + def _get_control_image(self, image, mask): + if "canny" in self.controlnet_method: + control_image = make_canny_control_image(image) + elif "openpose" in self.controlnet_method: + control_image = make_openpose_control_image(image) + elif "depth" in self.controlnet_method: + control_image = make_depth_control_image(image) + elif "inpaint" in self.controlnet_method: + control_image = make_inpaint_control_image(image, mask) + else: + raise NotImplementedError(f"{self.controlnet_method} not implemented") + return control_image + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + scheduler_config = self.model.scheduler.config + scheduler = get_scheduler(config.sd_sampler, scheduler_config) + self.model.scheduler = scheduler + + img_h, img_w = image.shape[:2] + control_image = self._get_control_image(image, mask) + mask_image = PIL.Image.fromarray(mask[:, :, -1], mode="L") + image = PIL.Image.fromarray(image) + + output = self.model( + image=image, + mask_image=mask_image, + control_image=control_image, + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + controlnet_conditioning_scale=config.controlnet_conditioning_scale, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/ddim_sampler.py b/py/iopaint/model/ddim_sampler.py new file mode 100644 index 0000000..a3f44fd --- /dev/null +++ b/py/iopaint/model/ddim_sampler.py @@ -0,0 +1,193 @@ +import torch +import numpy as np +from tqdm import tqdm + +from .utils import make_ddim_timesteps, make_ddim_sampling_parameters, noise_like + +from loguru import logger + + +class DDIMSampler(object): + def __init__(self, model, schedule="linear"): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + setattr(self, name, attr) + + def make_schedule( + self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0.0, verbose=True + ): + self.ddim_timesteps = make_ddim_timesteps( + ddim_discr_method=ddim_discretize, + num_ddim_timesteps=ddim_num_steps, + # array([1]) + num_ddpm_timesteps=self.ddpm_num_timesteps, + verbose=verbose, + ) + alphas_cumprod = self.model.alphas_cumprod # torch.Size([1000]) + assert ( + alphas_cumprod.shape[0] == self.ddpm_num_timesteps + ), "alphas have to be defined for each timestep" + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer("betas", to_torch(self.model.betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer( + "alphas_cumprod_prev", to_torch(self.model.alphas_cumprod_prev) + ) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer( + "sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", + to_torch(np.sqrt(1.0 - alphas_cumprod.cpu())), + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod.cpu())) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", + to_torch(np.sqrt(1.0 / alphas_cumprod.cpu() - 1)), + ) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters( + alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, + verbose=verbose, + ) + self.register_buffer("ddim_sigmas", ddim_sigmas) + self.register_buffer("ddim_alphas", ddim_alphas) + self.register_buffer("ddim_alphas_prev", ddim_alphas_prev) + self.register_buffer("ddim_sqrt_one_minus_alphas", np.sqrt(1.0 - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) + / (1 - self.alphas_cumprod) + * (1 - self.alphas_cumprod / self.alphas_cumprod_prev) + ) + self.register_buffer( + "ddim_sigmas_for_original_num_steps", sigmas_for_original_sampling_steps + ) + + @torch.no_grad() + def sample(self, steps, conditioning, batch_size, shape): + self.make_schedule(ddim_num_steps=steps, ddim_eta=0, verbose=False) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + + # samples: 1,3,128,128 + return self.ddim_sampling( + conditioning, + size, + quantize_denoised=False, + ddim_use_original_steps=False, + noise_dropout=0, + temperature=1.0, + ) + + @torch.no_grad() + def ddim_sampling( + self, + cond, + shape, + ddim_use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + ): + device = self.model.betas.device + b = shape[0] + img = torch.randn(shape, device=device, dtype=cond.dtype) + timesteps = ( + self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + ) + + time_range = ( + reversed(range(0, timesteps)) + if ddim_use_original_steps + else np.flip(timesteps) + ) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + logger.info(f"Running DDIM Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc="DDIM Sampler", total=total_steps) + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + + outs = self.p_sample_ddim( + img, + cond, + ts, + index=index, + use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, + temperature=temperature, + noise_dropout=noise_dropout, + ) + img, _ = outs + + return img + + @torch.no_grad() + def p_sample_ddim( + self, + x, + c, + t, + index, + repeat_noise=False, + use_original_steps=False, + quantize_denoised=False, + temperature=1.0, + noise_dropout=0.0, + ): + b, *_, device = *x.shape, x.device + e_t = self.model.apply_model(x, t, c) + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = ( + self.model.alphas_cumprod_prev + if use_original_steps + else self.ddim_alphas_prev + ) + sqrt_one_minus_alphas = ( + self.model.sqrt_one_minus_alphas_cumprod + if use_original_steps + else self.ddim_sqrt_one_minus_alphas + ) + sigmas = ( + self.model.ddim_sigmas_for_original_num_steps + if use_original_steps + else self.ddim_sigmas + ) + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full( + (b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device + ) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: # 没用 + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + # direction pointing to x_t + dir_xt = (1.0 - a_prev - sigma_t ** 2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.0: # 没用 + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 diff --git a/py/iopaint/model/fcf.py b/py/iopaint/model/fcf.py new file mode 100644 index 0000000..0eb2c1f --- /dev/null +++ b/py/iopaint/model/fcf.py @@ -0,0 +1,1737 @@ +import os +import random + +import cv2 +import torch +import numpy as np +import torch.fft as fft + +from ..schema import InpaintRequest + +from ..helper import ( + load_model, + get_cache_path_by_url, + norm_img, + boxes_from_mask, + resize_max_size, + download_model, +) +from .base import InpaintModel +from torch import conv2d, nn +import torch.nn.functional as F + +from .utils import ( + setup_filter, + _parse_scaling, + _parse_padding, + Conv2dLayer, + FullyConnectedLayer, + MinibatchStdLayer, + activation_funcs, + conv2d_resample, + bias_act, + upsample2d, + normalize_2nd_moment, + downsample2d, +) + + +def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"): + assert isinstance(x, torch.Tensor) + return _upfirdn2d_ref( + x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain + ) + + +def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): + """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.""" + # Validate arguments. + assert isinstance(x, torch.Tensor) and x.ndim == 4 + if f is None: + f = torch.ones([1, 1], dtype=torch.float32, device=x.device) + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + assert f.dtype == torch.float32 and not f.requires_grad + batch_size, num_channels, in_height, in_width = x.shape + upx, upy = _parse_scaling(up) + downx, downy = _parse_scaling(down) + padx0, padx1, pady0, pady1 = _parse_padding(padding) + + # Upsample by inserting zeros. + x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) + x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) + x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) + + # Pad or crop. + x = torch.nn.functional.pad( + x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)] + ) + x = x[ + :, + :, + max(-pady0, 0) : x.shape[2] - max(-pady1, 0), + max(-padx0, 0) : x.shape[3] - max(-padx1, 0), + ] + + # Setup filter. + f = f * (gain ** (f.ndim / 2)) + f = f.to(x.dtype) + if not flip_filter: + f = f.flip(list(range(f.ndim))) + + # Convolve with the filter. + f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) + if f.ndim == 4: + x = conv2d(input=x, weight=f, groups=num_channels) + else: + x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) + x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) + + # Downsample by throwing away pixels. + x = x[:, :, ::downy, ::downx] + return x + + +class EncoderEpilogue(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + cmap_dim, # Dimensionality of mapped conditioning label, 0 = no label. + z_dim, # Output Latent (Z) dimensionality. + resolution, # Resolution of this block. + img_channels, # Number of input color channels. + architecture="resnet", # Architecture: 'orig', 'skip', 'resnet'. + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + ): + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.cmap_dim = cmap_dim + self.resolution = resolution + self.img_channels = img_channels + self.architecture = architecture + + if architecture == "skip": + self.fromrgb = Conv2dLayer( + self.img_channels, in_channels, kernel_size=1, activation=activation + ) + self.mbstd = ( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + if mbstd_num_channels > 0 + else None + ) + self.conv = Conv2dLayer( + in_channels + mbstd_num_channels, + in_channels, + kernel_size=3, + activation=activation, + conv_clamp=conv_clamp, + ) + self.fc = FullyConnectedLayer( + in_channels * (resolution**2), z_dim, activation=activation + ) + self.dropout = torch.nn.Dropout(p=0.5) + + def forward(self, x, cmap, force_fp32=False): + _ = force_fp32 # unused + dtype = torch.float32 + memory_format = torch.contiguous_format + + # FromRGB. + x = x.to(dtype=dtype, memory_format=memory_format) + + # Main layers. + if self.mbstd is not None: + x = self.mbstd(x) + const_e = self.conv(x) + x = self.fc(const_e.flatten(1)) + x = self.dropout(x) + + # Conditioning. + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + assert x.dtype == dtype + return x, const_e + + +class EncoderBlock(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels, 0 = first block. + tmp_channels, # Number of intermediate channels. + out_channels, # Number of output channels. + resolution, # Resolution of this block. + img_channels, # Number of input color channels. + first_layer_idx, # Index of the first layer. + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + use_fp16=False, # Use FP16 for this block? + fp16_channels_last=False, # Use channels-last memory format with FP16? + freeze_layers=0, # Freeze-D: Number of layers to freeze. + ): + assert in_channels in [0, tmp_channels] + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.resolution = resolution + self.img_channels = img_channels + 1 + self.first_layer_idx = first_layer_idx + self.architecture = architecture + self.use_fp16 = use_fp16 + self.channels_last = use_fp16 and fp16_channels_last + self.register_buffer("resample_filter", setup_filter(resample_filter)) + + self.num_layers = 0 + + def trainable_gen(): + while True: + layer_idx = self.first_layer_idx + self.num_layers + trainable = layer_idx >= freeze_layers + self.num_layers += 1 + yield trainable + + trainable_iter = trainable_gen() + + if in_channels == 0: + self.fromrgb = Conv2dLayer( + self.img_channels, + tmp_channels, + kernel_size=1, + activation=activation, + trainable=next(trainable_iter), + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + self.conv0 = Conv2dLayer( + tmp_channels, + tmp_channels, + kernel_size=3, + activation=activation, + trainable=next(trainable_iter), + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + self.conv1 = Conv2dLayer( + tmp_channels, + out_channels, + kernel_size=3, + activation=activation, + down=2, + trainable=next(trainable_iter), + resample_filter=resample_filter, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + + if architecture == "resnet": + self.skip = Conv2dLayer( + tmp_channels, + out_channels, + kernel_size=1, + bias=False, + down=2, + trainable=next(trainable_iter), + resample_filter=resample_filter, + channels_last=self.channels_last, + ) + + def forward(self, x, img, force_fp32=False): + # dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32 + dtype = torch.float32 + memory_format = ( + torch.channels_last + if self.channels_last and not force_fp32 + else torch.contiguous_format + ) + + # Input. + if x is not None: + x = x.to(dtype=dtype, memory_format=memory_format) + + # FromRGB. + if self.in_channels == 0: + img = img.to(dtype=dtype, memory_format=memory_format) + y = self.fromrgb(img) + x = x + y if x is not None else y + img = ( + downsample2d(img, self.resample_filter) + if self.architecture == "skip" + else None + ) + + # Main layers. + if self.architecture == "resnet": + y = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0(x) + feat = x.clone() + x = self.conv1(x, gain=np.sqrt(0.5)) + x = y.add_(x) + else: + x = self.conv0(x) + feat = x.clone() + x = self.conv1(x) + + assert x.dtype == dtype + return x, img, feat + + +class EncoderNetwork(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + z_dim, # Input latent (Z) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + architecture="orig", # Architecture: 'orig', 'skip', 'resnet'. + channel_base=16384, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + num_fp16_res=0, # Use FP16 for the N highest resolutions. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + block_kwargs={}, # Arguments for DiscriminatorBlock. + mapping_kwargs={}, # Arguments for MappingNetwork. + epilogue_kwargs={}, # Arguments for EncoderEpilogue. + ): + super().__init__() + self.c_dim = c_dim + self.z_dim = z_dim + self.img_resolution = img_resolution + self.img_resolution_log2 = int(np.log2(img_resolution)) + self.img_channels = img_channels + self.block_resolutions = [ + 2**i for i in range(self.img_resolution_log2, 2, -1) + ] + channels_dict = { + res: min(channel_base // res, channel_max) + for res in self.block_resolutions + [4] + } + fp16_resolution = max(2 ** (self.img_resolution_log2 + 1 - num_fp16_res), 8) + + if cmap_dim is None: + cmap_dim = channels_dict[4] + if c_dim == 0: + cmap_dim = 0 + + common_kwargs = dict( + img_channels=img_channels, architecture=architecture, conv_clamp=conv_clamp + ) + cur_layer_idx = 0 + for res in self.block_resolutions: + in_channels = channels_dict[res] if res < img_resolution else 0 + tmp_channels = channels_dict[res] + out_channels = channels_dict[res // 2] + use_fp16 = res >= fp16_resolution + use_fp16 = False + block = EncoderBlock( + in_channels, + tmp_channels, + out_channels, + resolution=res, + first_layer_idx=cur_layer_idx, + use_fp16=use_fp16, + **block_kwargs, + **common_kwargs, + ) + setattr(self, f"b{res}", block) + cur_layer_idx += block.num_layers + if c_dim > 0: + self.mapping = MappingNetwork( + z_dim=0, + c_dim=c_dim, + w_dim=cmap_dim, + num_ws=None, + w_avg_beta=None, + **mapping_kwargs, + ) + self.b4 = EncoderEpilogue( + channels_dict[4], + cmap_dim=cmap_dim, + z_dim=z_dim * 2, + resolution=4, + **epilogue_kwargs, + **common_kwargs, + ) + + def forward(self, img, c, **block_kwargs): + x = None + feats = {} + for res in self.block_resolutions: + block = getattr(self, f"b{res}") + x, img, feat = block(x, img, **block_kwargs) + feats[res] = feat + + cmap = None + if self.c_dim > 0: + cmap = self.mapping(None, c) + x, const_e = self.b4(x, cmap) + feats[4] = const_e + + B, _ = x.shape + z = torch.zeros( + (B, self.z_dim), requires_grad=False, dtype=x.dtype, device=x.device + ) ## Noise for Co-Modulation + return x, z, feats + + +def fma(a, b, c): # => a * b + c + return _FusedMultiplyAdd.apply(a, b, c) + + +class _FusedMultiplyAdd(torch.autograd.Function): # a * b + c + @staticmethod + def forward(ctx, a, b, c): # pylint: disable=arguments-differ + out = torch.addcmul(c, a, b) + ctx.save_for_backward(a, b) + ctx.c_shape = c.shape + return out + + @staticmethod + def backward(ctx, dout): # pylint: disable=arguments-differ + a, b = ctx.saved_tensors + c_shape = ctx.c_shape + da = None + db = None + dc = None + + if ctx.needs_input_grad[0]: + da = _unbroadcast(dout * b, a.shape) + + if ctx.needs_input_grad[1]: + db = _unbroadcast(dout * a, b.shape) + + if ctx.needs_input_grad[2]: + dc = _unbroadcast(dout, c_shape) + + return da, db, dc + + +def _unbroadcast(x, shape): + extra_dims = x.ndim - len(shape) + assert extra_dims >= 0 + dim = [ + i + for i in range(x.ndim) + if x.shape[i] > 1 and (i < extra_dims or shape[i - extra_dims] == 1) + ] + if len(dim): + x = x.sum(dim=dim, keepdim=True) + if extra_dims: + x = x.reshape(-1, *x.shape[extra_dims + 1 :]) + assert x.shape == shape + return x + + +def modulated_conv2d( + x, # Input tensor of shape [batch_size, in_channels, in_height, in_width]. + weight, # Weight tensor of shape [out_channels, in_channels, kernel_height, kernel_width]. + styles, # Modulation coefficients of shape [batch_size, in_channels]. + noise=None, # Optional noise tensor to add to the output activations. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + padding=0, # Padding with respect to the upsampled image. + resample_filter=None, + # Low-pass filter to apply when resampling activations. Must be prepared beforehand by calling upfirdn2d.setup_filter(). + demodulate=True, # Apply weight demodulation? + flip_weight=True, # False = convolution, True = correlation (matches torch.nn.functional.conv2d). + fused_modconv=True, # Perform modulation, convolution, and demodulation as a single fused operation? +): + batch_size = x.shape[0] + out_channels, in_channels, kh, kw = weight.shape + + # Pre-normalize inputs to avoid FP16 overflow. + if x.dtype == torch.float16 and demodulate: + weight = weight * ( + 1 + / np.sqrt(in_channels * kh * kw) + / weight.norm(float("inf"), dim=[1, 2, 3], keepdim=True) + ) # max_Ikk + styles = styles / styles.norm(float("inf"), dim=1, keepdim=True) # max_I + + # Calculate per-sample weights and demodulation coefficients. + w = None + dcoefs = None + if demodulate or fused_modconv: + w = weight.unsqueeze(0) # [NOIkk] + w = w * styles.reshape(batch_size, 1, -1, 1, 1) # [NOIkk] + if demodulate: + dcoefs = (w.square().sum(dim=[2, 3, 4]) + 1e-8).rsqrt() # [NO] + if demodulate and fused_modconv: + w = w * dcoefs.reshape(batch_size, -1, 1, 1, 1) # [NOIkk] + # Execute by scaling the activations before and after the convolution. + if not fused_modconv: + x = x * styles.to(x.dtype).reshape(batch_size, -1, 1, 1) + x = conv2d_resample.conv2d_resample( + x=x, + w=weight.to(x.dtype), + f=resample_filter, + up=up, + down=down, + padding=padding, + flip_weight=flip_weight, + ) + if demodulate and noise is not None: + x = fma( + x, dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1), noise.to(x.dtype) + ) + elif demodulate: + x = x * dcoefs.to(x.dtype).reshape(batch_size, -1, 1, 1) + elif noise is not None: + x = x.add_(noise.to(x.dtype)) + return x + + # Execute as one fused op using grouped convolution. + batch_size = int(batch_size) + x = x.reshape(1, -1, *x.shape[2:]) + w = w.reshape(-1, in_channels, kh, kw) + x = conv2d_resample( + x=x, + w=w.to(x.dtype), + f=resample_filter, + up=up, + down=down, + padding=padding, + groups=batch_size, + flip_weight=flip_weight, + ) + x = x.reshape(batch_size, -1, *x.shape[2:]) + if noise is not None: + x = x.add_(noise) + return x + + +class SynthesisLayer(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + w_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this layer. + kernel_size=3, # Convolution kernel size. + up=1, # Integer upsampling factor. + use_noise=True, # Enable noise input? + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + channels_last=False, # Use channels_last format for the weights? + ): + super().__init__() + self.resolution = resolution + self.up = up + self.use_noise = use_noise + self.activation = activation + self.conv_clamp = conv_clamp + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.padding = kernel_size // 2 + self.act_gain = activation_funcs[activation].def_gain + + self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1) + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + self.weight = torch.nn.Parameter( + torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + ) + if use_noise: + self.register_buffer("noise_const", torch.randn([resolution, resolution])) + self.noise_strength = torch.nn.Parameter(torch.zeros([])) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + + def forward(self, x, w, noise_mode="none", fused_modconv=True, gain=1): + assert noise_mode in ["random", "const", "none"] + in_resolution = self.resolution // self.up + styles = self.affine(w) + + noise = None + if self.use_noise and noise_mode == "random": + noise = ( + torch.randn( + [x.shape[0], 1, self.resolution, self.resolution], device=x.device + ) + * self.noise_strength + ) + if self.use_noise and noise_mode == "const": + noise = self.noise_const * self.noise_strength + + flip_weight = self.up == 1 # slightly faster + x = modulated_conv2d( + x=x, + weight=self.weight, + styles=styles, + noise=noise, + up=self.up, + padding=self.padding, + resample_filter=self.resample_filter, + flip_weight=flip_weight, + fused_modconv=fused_modconv, + ) + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + x = F.leaky_relu(x, negative_slope=0.2, inplace=False) + if act_gain != 1: + x = x * act_gain + if act_clamp is not None: + x = x.clamp(-act_clamp, act_clamp) + return x + + +class ToRGBLayer(torch.nn.Module): + def __init__( + self, + in_channels, + out_channels, + w_dim, + kernel_size=1, + conv_clamp=None, + channels_last=False, + ): + super().__init__() + self.conv_clamp = conv_clamp + self.affine = FullyConnectedLayer(w_dim, in_channels, bias_init=1) + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + self.weight = torch.nn.Parameter( + torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + ) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + + def forward(self, x, w, fused_modconv=True): + styles = self.affine(w) * self.weight_gain + x = modulated_conv2d( + x=x, + weight=self.weight, + styles=styles, + demodulate=False, + fused_modconv=fused_modconv, + ) + x = bias_act(x, self.bias.to(x.dtype), clamp=self.conv_clamp) + return x + + +class SynthesisForeword(torch.nn.Module): + def __init__( + self, + z_dim, # Output Latent (Z) dimensionality. + resolution, # Resolution of this block. + in_channels, + img_channels, # Number of input color channels. + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + ): + super().__init__() + self.in_channels = in_channels + self.z_dim = z_dim + self.resolution = resolution + self.img_channels = img_channels + self.architecture = architecture + + self.fc = FullyConnectedLayer( + self.z_dim, (self.z_dim // 2) * 4 * 4, activation=activation + ) + self.conv = SynthesisLayer( + self.in_channels, self.in_channels, w_dim=(z_dim // 2) * 3, resolution=4 + ) + + if architecture == "skip": + self.torgb = ToRGBLayer( + self.in_channels, + self.img_channels, + kernel_size=1, + w_dim=(z_dim // 2) * 3, + ) + + def forward(self, x, ws, feats, img, force_fp32=False): + _ = force_fp32 # unused + dtype = torch.float32 + memory_format = torch.contiguous_format + + x_global = x.clone() + # ToRGB. + x = self.fc(x) + x = x.view(-1, self.z_dim // 2, 4, 4) + x = x.to(dtype=dtype, memory_format=memory_format) + + # Main layers. + x_skip = feats[4].clone() + x = x + x_skip + + mod_vector = [] + mod_vector.append(ws[:, 0]) + mod_vector.append(x_global.clone()) + mod_vector = torch.cat(mod_vector, dim=1) + + x = self.conv(x, mod_vector) + + mod_vector = [] + mod_vector.append(ws[:, 2 * 2 - 3]) + mod_vector.append(x_global.clone()) + mod_vector = torch.cat(mod_vector, dim=1) + + if self.architecture == "skip": + img = self.torgb(x, mod_vector) + img = img.to(dtype=torch.float32, memory_format=torch.contiguous_format) + + assert x.dtype == dtype + return x, img + + +class SELayer(nn.Module): + def __init__(self, channel, reduction=16): + super(SELayer, self).__init__() + self.avg_pool = nn.AdaptiveAvgPool2d(1) + self.fc = nn.Sequential( + nn.Linear(channel, channel // reduction, bias=False), + nn.ReLU(inplace=False), + nn.Linear(channel // reduction, channel, bias=False), + nn.Sigmoid(), + ) + + def forward(self, x): + b, c, _, _ = x.size() + y = self.avg_pool(x).view(b, c) + y = self.fc(y).view(b, c, 1, 1) + res = x * y.expand_as(x) + return res + + +class FourierUnit(nn.Module): + def __init__( + self, + in_channels, + out_channels, + groups=1, + spatial_scale_factor=None, + spatial_scale_mode="bilinear", + spectral_pos_encoding=False, + use_se=False, + se_kwargs=None, + ffc3d=False, + fft_norm="ortho", + ): + # bn_layer not used + super(FourierUnit, self).__init__() + self.groups = groups + + self.conv_layer = torch.nn.Conv2d( + in_channels=in_channels * 2 + (2 if spectral_pos_encoding else 0), + out_channels=out_channels * 2, + kernel_size=1, + stride=1, + padding=0, + groups=self.groups, + bias=False, + ) + self.relu = torch.nn.ReLU(inplace=False) + + # squeeze and excitation block + self.use_se = use_se + if use_se: + if se_kwargs is None: + se_kwargs = {} + self.se = SELayer(self.conv_layer.in_channels, **se_kwargs) + + self.spatial_scale_factor = spatial_scale_factor + self.spatial_scale_mode = spatial_scale_mode + self.spectral_pos_encoding = spectral_pos_encoding + self.ffc3d = ffc3d + self.fft_norm = fft_norm + + def forward(self, x): + batch = x.shape[0] + + if self.spatial_scale_factor is not None: + orig_size = x.shape[-2:] + x = F.interpolate( + x, + scale_factor=self.spatial_scale_factor, + mode=self.spatial_scale_mode, + align_corners=False, + ) + + r_size = x.size() + # (batch, c, h, w/2+1, 2) + fft_dim = (-3, -2, -1) if self.ffc3d else (-2, -1) + ffted = fft.rfftn(x, dim=fft_dim, norm=self.fft_norm) + ffted = torch.stack((ffted.real, ffted.imag), dim=-1) + ffted = ffted.permute(0, 1, 4, 2, 3).contiguous() # (batch, c, 2, h, w/2+1) + ffted = ffted.view( + ( + batch, + -1, + ) + + ffted.size()[3:] + ) + + if self.spectral_pos_encoding: + height, width = ffted.shape[-2:] + coords_vert = ( + torch.linspace(0, 1, height)[None, None, :, None] + .expand(batch, 1, height, width) + .to(ffted) + ) + coords_hor = ( + torch.linspace(0, 1, width)[None, None, None, :] + .expand(batch, 1, height, width) + .to(ffted) + ) + ffted = torch.cat((coords_vert, coords_hor, ffted), dim=1) + + if self.use_se: + ffted = self.se(ffted) + + ffted = self.conv_layer(ffted) # (batch, c*2, h, w/2+1) + ffted = self.relu(ffted) + + ffted = ( + ffted.view( + ( + batch, + -1, + 2, + ) + + ffted.size()[2:] + ) + .permute(0, 1, 3, 4, 2) + .contiguous() + ) # (batch,c, t, h, w/2+1, 2) + ffted = torch.complex(ffted[..., 0], ffted[..., 1]) + + ifft_shape_slice = x.shape[-3:] if self.ffc3d else x.shape[-2:] + output = torch.fft.irfftn( + ffted, s=ifft_shape_slice, dim=fft_dim, norm=self.fft_norm + ) + + if self.spatial_scale_factor is not None: + output = F.interpolate( + output, + size=orig_size, + mode=self.spatial_scale_mode, + align_corners=False, + ) + + return output + + +class SpectralTransform(nn.Module): + def __init__( + self, + in_channels, + out_channels, + stride=1, + groups=1, + enable_lfu=True, + **fu_kwargs, + ): + # bn_layer not used + super(SpectralTransform, self).__init__() + self.enable_lfu = enable_lfu + if stride == 2: + self.downsample = nn.AvgPool2d(kernel_size=(2, 2), stride=2) + else: + self.downsample = nn.Identity() + + self.stride = stride + self.conv1 = nn.Sequential( + nn.Conv2d( + in_channels, out_channels // 2, kernel_size=1, groups=groups, bias=False + ), + # nn.BatchNorm2d(out_channels // 2), + nn.ReLU(inplace=True), + ) + self.fu = FourierUnit(out_channels // 2, out_channels // 2, groups, **fu_kwargs) + if self.enable_lfu: + self.lfu = FourierUnit(out_channels // 2, out_channels // 2, groups) + self.conv2 = torch.nn.Conv2d( + out_channels // 2, out_channels, kernel_size=1, groups=groups, bias=False + ) + + def forward(self, x): + x = self.downsample(x) + x = self.conv1(x) + output = self.fu(x) + + if self.enable_lfu: + n, c, h, w = x.shape + split_no = 2 + split_s = h // split_no + xs = torch.cat( + torch.split(x[:, : c // 4], split_s, dim=-2), dim=1 + ).contiguous() + xs = torch.cat(torch.split(xs, split_s, dim=-1), dim=1).contiguous() + xs = self.lfu(xs) + xs = xs.repeat(1, 1, split_no, split_no).contiguous() + else: + xs = 0 + + output = self.conv2(x + output + xs) + + return output + + +class FFC(nn.Module): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=False, + enable_lfu=True, + padding_type="reflect", + gated=False, + **spectral_kwargs, + ): + super(FFC, self).__init__() + + assert stride == 1 or stride == 2, "Stride should be 1 or 2." + self.stride = stride + + in_cg = int(in_channels * ratio_gin) + in_cl = in_channels - in_cg + out_cg = int(out_channels * ratio_gout) + out_cl = out_channels - out_cg + # groups_g = 1 if groups == 1 else int(groups * ratio_gout) + # groups_l = 1 if groups == 1 else groups - groups_g + + self.ratio_gin = ratio_gin + self.ratio_gout = ratio_gout + self.global_in_num = in_cg + + module = nn.Identity if in_cl == 0 or out_cl == 0 else nn.Conv2d + self.convl2l = module( + in_cl, + out_cl, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cl == 0 or out_cg == 0 else nn.Conv2d + self.convl2g = module( + in_cl, + out_cg, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cg == 0 or out_cl == 0 else nn.Conv2d + self.convg2l = module( + in_cg, + out_cl, + kernel_size, + stride, + padding, + dilation, + groups, + bias, + padding_mode=padding_type, + ) + module = nn.Identity if in_cg == 0 or out_cg == 0 else SpectralTransform + self.convg2g = module( + in_cg, + out_cg, + stride, + 1 if groups == 1 else groups // 2, + enable_lfu, + **spectral_kwargs, + ) + + self.gated = gated + module = ( + nn.Identity if in_cg == 0 or out_cl == 0 or not self.gated else nn.Conv2d + ) + self.gate = module(in_channels, 2, 1) + + def forward(self, x, fname=None): + x_l, x_g = x if type(x) is tuple else (x, 0) + out_xl, out_xg = 0, 0 + + if self.gated: + total_input_parts = [x_l] + if torch.is_tensor(x_g): + total_input_parts.append(x_g) + total_input = torch.cat(total_input_parts, dim=1) + + gates = torch.sigmoid(self.gate(total_input)) + g2l_gate, l2g_gate = gates.chunk(2, dim=1) + else: + g2l_gate, l2g_gate = 1, 1 + + spec_x = self.convg2g(x_g) + + if self.ratio_gout != 1: + out_xl = self.convl2l(x_l) + self.convg2l(x_g) * g2l_gate + if self.ratio_gout != 0: + out_xg = self.convl2g(x_l) * l2g_gate + spec_x + + return out_xl, out_xg + + +class FFC_BN_ACT(nn.Module): + def __init__( + self, + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride=1, + padding=0, + dilation=1, + groups=1, + bias=False, + norm_layer=nn.SyncBatchNorm, + activation_layer=nn.Identity, + padding_type="reflect", + enable_lfu=True, + **kwargs, + ): + super(FFC_BN_ACT, self).__init__() + self.ffc = FFC( + in_channels, + out_channels, + kernel_size, + ratio_gin, + ratio_gout, + stride, + padding, + dilation, + groups, + bias, + enable_lfu, + padding_type=padding_type, + **kwargs, + ) + lnorm = nn.Identity if ratio_gout == 1 else norm_layer + gnorm = nn.Identity if ratio_gout == 0 else norm_layer + global_channels = int(out_channels * ratio_gout) + # self.bn_l = lnorm(out_channels - global_channels) + # self.bn_g = gnorm(global_channels) + + lact = nn.Identity if ratio_gout == 1 else activation_layer + gact = nn.Identity if ratio_gout == 0 else activation_layer + self.act_l = lact(inplace=True) + self.act_g = gact(inplace=True) + + def forward(self, x, fname=None): + x_l, x_g = self.ffc( + x, + fname=fname, + ) + x_l = self.act_l(x_l) + x_g = self.act_g(x_g) + return x_l, x_g + + +class FFCResnetBlock(nn.Module): + def __init__( + self, + dim, + padding_type, + norm_layer, + activation_layer=nn.ReLU, + dilation=1, + spatial_transform_kwargs=None, + inline=False, + ratio_gin=0.75, + ratio_gout=0.75, + ): + super().__init__() + self.conv1 = FFC_BN_ACT( + dim, + dim, + kernel_size=3, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + activation_layer=activation_layer, + padding_type=padding_type, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + self.conv2 = FFC_BN_ACT( + dim, + dim, + kernel_size=3, + padding=dilation, + dilation=dilation, + norm_layer=norm_layer, + activation_layer=activation_layer, + padding_type=padding_type, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + self.inline = inline + + def forward(self, x, fname=None): + if self.inline: + x_l, x_g = ( + x[:, : -self.conv1.ffc.global_in_num], + x[:, -self.conv1.ffc.global_in_num :], + ) + else: + x_l, x_g = x if type(x) is tuple else (x, 0) + + id_l, id_g = x_l, x_g + + x_l, x_g = self.conv1((x_l, x_g), fname=fname) + x_l, x_g = self.conv2((x_l, x_g), fname=fname) + + x_l, x_g = id_l + x_l, id_g + x_g + out = x_l, x_g + if self.inline: + out = torch.cat(out, dim=1) + return out + + +class ConcatTupleLayer(nn.Module): + def forward(self, x): + assert isinstance(x, tuple) + x_l, x_g = x + assert torch.is_tensor(x_l) or torch.is_tensor(x_g) + if not torch.is_tensor(x_g): + return x_l + return torch.cat(x, dim=1) + + +class FFCBlock(torch.nn.Module): + def __init__( + self, + dim, # Number of output/input channels. + kernel_size, # Width and height of the convolution kernel. + padding, + ratio_gin=0.75, + ratio_gout=0.75, + activation="linear", # Activation function: 'relu', 'lrelu', etc. + ): + super().__init__() + if activation == "linear": + self.activation = nn.Identity + else: + self.activation = nn.ReLU + self.padding = padding + self.kernel_size = kernel_size + self.ffc_block = FFCResnetBlock( + dim=dim, + padding_type="reflect", + norm_layer=nn.SyncBatchNorm, + activation_layer=self.activation, + dilation=1, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + + self.concat_layer = ConcatTupleLayer() + + def forward(self, gen_ft, mask, fname=None): + x = gen_ft.float() + + x_l, x_g = ( + x[:, : -self.ffc_block.conv1.ffc.global_in_num], + x[:, -self.ffc_block.conv1.ffc.global_in_num :], + ) + id_l, id_g = x_l, x_g + + x_l, x_g = self.ffc_block((x_l, x_g), fname=fname) + x_l, x_g = id_l + x_l, id_g + x_g + x = self.concat_layer((x_l, x_g)) + + return x + gen_ft.float() + + +class FFCSkipLayer(torch.nn.Module): + def __init__( + self, + dim, # Number of input/output channels. + kernel_size=3, # Convolution kernel size. + ratio_gin=0.75, + ratio_gout=0.75, + ): + super().__init__() + self.padding = kernel_size // 2 + + self.ffc_act = FFCBlock( + dim=dim, + kernel_size=kernel_size, + activation=nn.ReLU, + padding=self.padding, + ratio_gin=ratio_gin, + ratio_gout=ratio_gout, + ) + + def forward(self, gen_ft, mask, fname=None): + x = self.ffc_act(gen_ft, mask, fname=fname) + return x + + +class SynthesisBlock(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels, 0 = first block. + out_channels, # Number of output channels. + w_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this block. + img_channels, # Number of output color channels. + is_last, # Is this the last block? + architecture="skip", # Architecture: 'orig', 'skip', 'resnet'. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + use_fp16=False, # Use FP16 for this block? + fp16_channels_last=False, # Use channels-last memory format with FP16? + **layer_kwargs, # Arguments for SynthesisLayer. + ): + assert architecture in ["orig", "skip", "resnet"] + super().__init__() + self.in_channels = in_channels + self.w_dim = w_dim + self.resolution = resolution + self.img_channels = img_channels + self.is_last = is_last + self.architecture = architecture + self.use_fp16 = use_fp16 + self.channels_last = use_fp16 and fp16_channels_last + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.num_conv = 0 + self.num_torgb = 0 + self.res_ffc = {4: 0, 8: 0, 16: 0, 32: 1, 64: 1, 128: 1, 256: 1, 512: 1} + + if in_channels != 0 and resolution >= 8: + self.ffc_skip = nn.ModuleList() + for _ in range(self.res_ffc[resolution]): + self.ffc_skip.append(FFCSkipLayer(dim=out_channels)) + + if in_channels == 0: + self.const = torch.nn.Parameter( + torch.randn([out_channels, resolution, resolution]) + ) + + if in_channels != 0: + self.conv0 = SynthesisLayer( + in_channels, + out_channels, + w_dim=w_dim * 3, + resolution=resolution, + up=2, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + **layer_kwargs, + ) + self.num_conv += 1 + + self.conv1 = SynthesisLayer( + out_channels, + out_channels, + w_dim=w_dim * 3, + resolution=resolution, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + **layer_kwargs, + ) + self.num_conv += 1 + + if is_last or architecture == "skip": + self.torgb = ToRGBLayer( + out_channels, + img_channels, + w_dim=w_dim * 3, + conv_clamp=conv_clamp, + channels_last=self.channels_last, + ) + self.num_torgb += 1 + + if in_channels != 0 and architecture == "resnet": + self.skip = Conv2dLayer( + in_channels, + out_channels, + kernel_size=1, + bias=False, + up=2, + resample_filter=resample_filter, + channels_last=self.channels_last, + ) + + def forward( + self, + x, + mask, + feats, + img, + ws, + fname=None, + force_fp32=False, + fused_modconv=None, + **layer_kwargs, + ): + dtype = torch.float16 if self.use_fp16 and not force_fp32 else torch.float32 + dtype = torch.float32 + memory_format = ( + torch.channels_last + if self.channels_last and not force_fp32 + else torch.contiguous_format + ) + if fused_modconv is None: + fused_modconv = (not self.training) and ( + dtype == torch.float32 or int(x.shape[0]) == 1 + ) + + x = x.to(dtype=dtype, memory_format=memory_format) + x_skip = ( + feats[self.resolution].clone().to(dtype=dtype, memory_format=memory_format) + ) + + # Main layers. + if self.in_channels == 0: + x = self.conv1(x, ws[1], fused_modconv=fused_modconv, **layer_kwargs) + elif self.architecture == "resnet": + y = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0( + x, ws[0].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + if len(self.ffc_skip) > 0: + mask = F.interpolate( + mask, + size=x_skip.shape[2:], + ) + z = x + x_skip + for fres in self.ffc_skip: + z = fres(z, mask) + x = x + z + else: + x = x + x_skip + x = self.conv1( + x, + ws[1].clone(), + fused_modconv=fused_modconv, + gain=np.sqrt(0.5), + **layer_kwargs, + ) + x = y.add_(x) + else: + x = self.conv0( + x, ws[0].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + if len(self.ffc_skip) > 0: + mask = F.interpolate( + mask, + size=x_skip.shape[2:], + ) + z = x + x_skip + for fres in self.ffc_skip: + z = fres(z, mask) + x = x + z + else: + x = x + x_skip + x = self.conv1( + x, ws[1].clone(), fused_modconv=fused_modconv, **layer_kwargs + ) + # ToRGB. + if img is not None: + img = upsample2d(img, self.resample_filter) + if self.is_last or self.architecture == "skip": + y = self.torgb(x, ws[2].clone(), fused_modconv=fused_modconv) + y = y.to(dtype=torch.float32, memory_format=torch.contiguous_format) + img = img.add_(y) if img is not None else y + + x = x.to(dtype=dtype) + assert x.dtype == dtype + assert img is None or img.dtype == torch.float32 + return x, img + + +class SynthesisNetwork(torch.nn.Module): + def __init__( + self, + w_dim, # Intermediate latent (W) dimensionality. + z_dim, # Output Latent (Z) dimensionality. + img_resolution, # Output image resolution. + img_channels, # Number of color channels. + channel_base=16384, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + num_fp16_res=0, # Use FP16 for the N highest resolutions. + **block_kwargs, # Arguments for SynthesisBlock. + ): + assert img_resolution >= 4 and img_resolution & (img_resolution - 1) == 0 + super().__init__() + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_resolution_log2 = int(np.log2(img_resolution)) + self.img_channels = img_channels + self.block_resolutions = [ + 2**i for i in range(3, self.img_resolution_log2 + 1) + ] + channels_dict = { + res: min(channel_base // res, channel_max) for res in self.block_resolutions + } + fp16_resolution = max(2 ** (self.img_resolution_log2 + 1 - num_fp16_res), 8) + + self.foreword = SynthesisForeword( + img_channels=img_channels, + in_channels=min(channel_base // 4, channel_max), + z_dim=z_dim * 2, + resolution=4, + ) + + self.num_ws = self.img_resolution_log2 * 2 - 2 + for res in self.block_resolutions: + if res // 2 in channels_dict.keys(): + in_channels = channels_dict[res // 2] if res > 4 else 0 + else: + in_channels = min(channel_base // (res // 2), channel_max) + out_channels = channels_dict[res] + use_fp16 = res >= fp16_resolution + use_fp16 = False + is_last = res == self.img_resolution + block = SynthesisBlock( + in_channels, + out_channels, + w_dim=w_dim, + resolution=res, + img_channels=img_channels, + is_last=is_last, + use_fp16=use_fp16, + **block_kwargs, + ) + setattr(self, f"b{res}", block) + + def forward(self, x_global, mask, feats, ws, fname=None, **block_kwargs): + img = None + + x, img = self.foreword(x_global, ws, feats, img) + + for res in self.block_resolutions: + block = getattr(self, f"b{res}") + mod_vector0 = [] + mod_vector0.append(ws[:, int(np.log2(res)) * 2 - 5]) + mod_vector0.append(x_global.clone()) + mod_vector0 = torch.cat(mod_vector0, dim=1) + + mod_vector1 = [] + mod_vector1.append(ws[:, int(np.log2(res)) * 2 - 4]) + mod_vector1.append(x_global.clone()) + mod_vector1 = torch.cat(mod_vector1, dim=1) + + mod_vector_rgb = [] + mod_vector_rgb.append(ws[:, int(np.log2(res)) * 2 - 3]) + mod_vector_rgb.append(x_global.clone()) + mod_vector_rgb = torch.cat(mod_vector_rgb, dim=1) + x, img = block( + x, + mask, + feats, + img, + (mod_vector0, mod_vector1, mod_vector_rgb), + fname=fname, + **block_kwargs, + ) + return img + + +class MappingNetwork(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + num_ws, # Number of intermediate latents to output, None = do not broadcast. + num_layers=8, # Number of mapping layers. + embed_features=None, # Label embedding dimensionality, None = same as w_dim. + layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. + w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.num_ws = num_ws + self.num_layers = num_layers + self.w_avg_beta = w_avg_beta + + if embed_features is None: + embed_features = w_dim + if c_dim == 0: + embed_features = 0 + if layer_features is None: + layer_features = w_dim + features_list = ( + [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim] + ) + + if c_dim > 0: + self.embed = FullyConnectedLayer(c_dim, embed_features) + for idx in range(num_layers): + in_features = features_list[idx] + out_features = features_list[idx + 1] + layer = FullyConnectedLayer( + in_features, + out_features, + activation=activation, + lr_multiplier=lr_multiplier, + ) + setattr(self, f"fc{idx}", layer) + + if num_ws is not None and w_avg_beta is not None: + self.register_buffer("w_avg", torch.zeros([w_dim])) + + def forward( + self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False + ): + # Embed, normalize, and concat inputs. + x = None + with torch.autograd.profiler.record_function("input"): + if self.z_dim > 0: + x = normalize_2nd_moment(z.to(torch.float32)) + if self.c_dim > 0: + y = normalize_2nd_moment(self.embed(c.to(torch.float32))) + x = torch.cat([x, y], dim=1) if x is not None else y + + # Main layers. + for idx in range(self.num_layers): + layer = getattr(self, f"fc{idx}") + x = layer(x) + + # Update moving average of W. + if self.w_avg_beta is not None and self.training and not skip_w_avg_update: + with torch.autograd.profiler.record_function("update_w_avg"): + self.w_avg.copy_( + x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta) + ) + + # Broadcast. + if self.num_ws is not None: + with torch.autograd.profiler.record_function("broadcast"): + x = x.unsqueeze(1).repeat([1, self.num_ws, 1]) + + # Apply truncation. + if truncation_psi != 1: + with torch.autograd.profiler.record_function("truncate"): + assert self.w_avg_beta is not None + if self.num_ws is None or truncation_cutoff is None: + x = self.w_avg.lerp(x, truncation_psi) + else: + x[:, :truncation_cutoff] = self.w_avg.lerp( + x[:, :truncation_cutoff], truncation_psi + ) + return x + + +class Generator(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality. + c_dim, # Conditioning label (C) dimensionality. + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # Output resolution. + img_channels, # Number of output color channels. + encoder_kwargs={}, # Arguments for EncoderNetwork. + mapping_kwargs={}, # Arguments for MappingNetwork. + synthesis_kwargs={}, # Arguments for SynthesisNetwork. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + self.encoder = EncoderNetwork( + c_dim=c_dim, + z_dim=z_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **encoder_kwargs, + ) + self.synthesis = SynthesisNetwork( + z_dim=z_dim, + w_dim=w_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **synthesis_kwargs, + ) + self.num_ws = self.synthesis.num_ws + self.mapping = MappingNetwork( + z_dim=z_dim, c_dim=c_dim, w_dim=w_dim, num_ws=self.num_ws, **mapping_kwargs + ) + + def forward( + self, + img, + c, + fname=None, + truncation_psi=1, + truncation_cutoff=None, + **synthesis_kwargs, + ): + mask = img[:, -1].unsqueeze(1) + x_global, z, feats = self.encoder(img, c) + ws = self.mapping( + z, c, truncation_psi=truncation_psi, truncation_cutoff=truncation_cutoff + ) + img = self.synthesis(x_global, mask, feats, ws, fname=fname, **synthesis_kwargs) + return img + + +FCF_MODEL_URL = os.environ.get( + "FCF_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_fcf/places_512_G.pth", +) +FCF_MODEL_MD5 = os.environ.get("FCF_MODEL_MD5", "3323152bc01bf1c56fd8aba74435a211") + + +class FcF(InpaintModel): + name = "fcf" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + seed = 0 + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + torch.backends.cudnn.deterministic = True + torch.backends.cudnn.benchmark = False + + kwargs = { + "channel_base": 1 * 32768, + "channel_max": 512, + "num_fp16_res": 4, + "conv_clamp": 256, + } + G = Generator( + z_dim=512, + c_dim=0, + w_dim=512, + img_resolution=512, + img_channels=3, + synthesis_kwargs=kwargs, + encoder_kwargs=kwargs, + mapping_kwargs={"num_layers": 2}, + ) + self.model = load_model(G, FCF_MODEL_URL, device, FCF_MODEL_MD5) + self.label = torch.zeros([1, self.model.c_dim], device=device) + + @staticmethod + def download(): + download_model(FCF_MODEL_URL, FCF_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(FCF_MODEL_URL)) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + if image.shape[0] == 512 and image.shape[1] == 512: + return self._pad_forward(image, mask, config) + + boxes = boxes_from_mask(mask) + crop_result = [] + config.hd_strategy_crop_margin = 128 + for box in boxes: + crop_image, crop_mask, crop_box = self._crop_box(image, mask, box, config) + origin_size = crop_image.shape[:2] + resize_image = resize_max_size(crop_image, size_limit=512) + resize_mask = resize_max_size(crop_mask, size_limit=512) + inpaint_result = self._pad_forward(resize_image, resize_mask, config) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + original_pixel_indices = crop_mask < 127 + inpaint_result[original_pixel_indices] = crop_image[:, :, ::-1][ + original_pixel_indices + ] + + crop_result.append((inpaint_result, crop_box)) + + inpaint_result = image[:, :, ::-1].copy() + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + return inpaint_result + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + mask = (mask > 120) * 255 + mask = norm_img(mask) + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + erased_img = image * (1 - mask) + input_image = torch.cat([0.5 - mask, erased_img], dim=1) + + output = self.model( + input_image, self.label, truncation_psi=0.1, noise_mode="none" + ) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/helper/__init__.py b/py/iopaint/model/helper/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/helper/controlnet_preprocess.py b/py/iopaint/model/helper/controlnet_preprocess.py new file mode 100644 index 0000000..1d2e542 --- /dev/null +++ b/py/iopaint/model/helper/controlnet_preprocess.py @@ -0,0 +1,68 @@ +import torch +import PIL +import cv2 +from PIL import Image +import numpy as np + +from ...helper import pad_img_to_modulo + + +def make_canny_control_image(image: np.ndarray) -> Image: + canny_image = cv2.Canny(image, 100, 200) + canny_image = canny_image[:, :, None] + canny_image = np.concatenate([canny_image, canny_image, canny_image], axis=2) + canny_image = PIL.Image.fromarray(canny_image) + control_image = canny_image + return control_image + + +def make_openpose_control_image(image: np.ndarray) -> Image: + from controlnet_aux import OpenposeDetector + + processor = OpenposeDetector.from_pretrained("lllyasviel/ControlNet") + control_image = processor(image, hand_and_face=True) + return control_image + + +def resize_image(input_image, resolution): + H, W, C = input_image.shape + H = float(H) + W = float(W) + k = float(resolution) / min(H, W) + H *= k + W *= k + H = int(np.round(H / 64.0)) * 64 + W = int(np.round(W / 64.0)) * 64 + img = cv2.resize( + input_image, + (W, H), + interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA, + ) + return img + + +def make_depth_control_image(image: np.ndarray) -> Image: + from controlnet_aux import MidasDetector + + midas = MidasDetector.from_pretrained("lllyasviel/Annotators") + + origin_height, origin_width = image.shape[:2] + pad_image = pad_img_to_modulo(image, mod=64, square=False, min_size=512) + depth_image = midas(pad_image) + depth_image = depth_image[0:origin_height, 0:origin_width] + depth_image = depth_image[:, :, None] + depth_image = np.concatenate([depth_image, depth_image, depth_image], axis=2) + control_image = PIL.Image.fromarray(depth_image) + return control_image + + +def make_inpaint_control_image(image: np.ndarray, mask: np.ndarray) -> torch.Tensor: + """ + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + """ + image = image.astype(np.float32) / 255.0 + image[mask[:, :, -1] > 128] = -1.0 # set as masked pixel + image = np.expand_dims(image, 0).transpose(0, 3, 1, 2) + image = torch.from_numpy(image) + return image diff --git a/py/iopaint/model/helper/cpu_text_encoder.py b/py/iopaint/model/helper/cpu_text_encoder.py new file mode 100644 index 0000000..116eb48 --- /dev/null +++ b/py/iopaint/model/helper/cpu_text_encoder.py @@ -0,0 +1,41 @@ +import torch +from transformers import PreTrainedModel + +from ..utils import torch_gc + + +class CPUTextEncoderWrapper(PreTrainedModel): + def __init__(self, text_encoder, torch_dtype): + super().__init__(text_encoder.config) + self.config = text_encoder.config + self._device = text_encoder.device + # cpu not support float16 + self.text_encoder = text_encoder.to(torch.device("cpu"), non_blocking=True) + self.text_encoder = self.text_encoder.to(torch.float32, non_blocking=True) + self.torch_dtype = torch_dtype + del text_encoder + torch_gc() + + def __call__(self, x, **kwargs): + input_device = x.device + original_output = self.text_encoder(x.to(self.text_encoder.device), **kwargs) + for k, v in original_output.items(): + if isinstance(v, tuple): + original_output[k] = [ + v[i].to(input_device).to(self.torch_dtype) for i in range(len(v)) + ] + else: + original_output[k] = v.to(input_device).to(self.torch_dtype) + return original_output + + @property + def dtype(self): + return self.torch_dtype + + @property + def device(self) -> torch.device: + """ + `torch.device`: The device on which the module is (assuming that all the module parameters are on the same + device). + """ + return self._device \ No newline at end of file diff --git a/py/iopaint/model/helper/g_diffuser_bot.py b/py/iopaint/model/helper/g_diffuser_bot.py new file mode 100644 index 0000000..a4147af --- /dev/null +++ b/py/iopaint/model/helper/g_diffuser_bot.py @@ -0,0 +1,167 @@ +# code copy from: https://github.com/parlance-zz/g-diffuser-bot +import cv2 +import numpy as np + + +def np_img_grey_to_rgb(data): + if data.ndim == 3: + return data + return np.expand_dims(data, 2) * np.ones((1, 1, 3)) + + +def convolve(data1, data2): # fast convolution with fft + if data1.ndim != data2.ndim: # promote to rgb if mismatch + if data1.ndim < 3: + data1 = np_img_grey_to_rgb(data1) + if data2.ndim < 3: + data2 = np_img_grey_to_rgb(data2) + return ifft2(fft2(data1) * fft2(data2)) + + +def fft2(data): + if data.ndim > 2: # multiple channels + out_fft = np.zeros( + (data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128 + ) + for c in range(data.shape[2]): + c_data = data[:, :, c] + out_fft[:, :, c] = np.fft.fft2(np.fft.fftshift(c_data), norm="ortho") + out_fft[:, :, c] = np.fft.ifftshift(out_fft[:, :, c]) + else: # single channel + out_fft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128) + out_fft[:, :] = np.fft.fft2(np.fft.fftshift(data), norm="ortho") + out_fft[:, :] = np.fft.ifftshift(out_fft[:, :]) + + return out_fft + + +def ifft2(data): + if data.ndim > 2: # multiple channels + out_ifft = np.zeros( + (data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128 + ) + for c in range(data.shape[2]): + c_data = data[:, :, c] + out_ifft[:, :, c] = np.fft.ifft2(np.fft.fftshift(c_data), norm="ortho") + out_ifft[:, :, c] = np.fft.ifftshift(out_ifft[:, :, c]) + else: # single channel + out_ifft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128) + out_ifft[:, :] = np.fft.ifft2(np.fft.fftshift(data), norm="ortho") + out_ifft[:, :] = np.fft.ifftshift(out_ifft[:, :]) + + return out_ifft + + +def get_gradient_kernel(width, height, std=3.14, mode="linear"): + window_scale_x = float( + width / min(width, height) + ) # for non-square aspect ratios we still want a circular kernel + window_scale_y = float(height / min(width, height)) + if mode == "gaussian": + x = (np.arange(width) / width * 2.0 - 1.0) * window_scale_x + kx = np.exp(-x * x * std) + if window_scale_x != window_scale_y: + y = (np.arange(height) / height * 2.0 - 1.0) * window_scale_y + ky = np.exp(-y * y * std) + else: + y = x + ky = kx + return np.outer(kx, ky) + elif mode == "linear": + x = (np.arange(width) / width * 2.0 - 1.0) * window_scale_x + if window_scale_x != window_scale_y: + y = (np.arange(height) / height * 2.0 - 1.0) * window_scale_y + else: + y = x + return np.clip(1.0 - np.sqrt(np.add.outer(x * x, y * y)) * std / 3.14, 0.0, 1.0) + else: + raise Exception("Error: Unknown mode in get_gradient_kernel: {0}".format(mode)) + + +def image_blur(data, std=3.14, mode="linear"): + width = data.shape[0] + height = data.shape[1] + kernel = get_gradient_kernel(width, height, std, mode=mode) + return np.real(convolve(data, kernel / np.sqrt(np.sum(kernel * kernel)))) + + +def soften_mask(mask_img, softness, space): + if softness == 0: + return mask_img + softness = min(softness, 1.0) + space = np.clip(space, 0.0, 1.0) + original_max_opacity = np.max(mask_img) + out_mask = mask_img <= 0.0 + blurred_mask = image_blur(mask_img, 3.5 / softness, mode="linear") + blurred_mask = np.maximum(blurred_mask - np.max(blurred_mask[out_mask]), 0.0) + mask_img *= blurred_mask # preserve partial opacity in original input mask + mask_img /= np.max(mask_img) # renormalize + mask_img = np.clip(mask_img - space, 0.0, 1.0) # make space + mask_img /= np.max(mask_img) # and renormalize again + mask_img *= original_max_opacity # restore original max opacity + return mask_img + + +def expand_image( + cv2_img, top: int, right: int, bottom: int, left: int, softness: float, space: float +): + assert cv2_img.shape[2] == 3 + origin_h, origin_w = cv2_img.shape[:2] + new_width = cv2_img.shape[1] + left + right + new_height = cv2_img.shape[0] + top + bottom + + # TODO: which is better? + # new_img = np.random.randint(0, 255, (new_height, new_width, 3), np.uint8) + new_img = cv2.copyMakeBorder( + cv2_img, top, bottom, left, right, cv2.BORDER_REPLICATE + ) + mask_img = np.zeros((new_height, new_width), np.uint8) + mask_img[top : top + cv2_img.shape[0], left : left + cv2_img.shape[1]] = 255 + + if softness > 0.0: + mask_img = soften_mask(mask_img / 255.0, softness / 100.0, space / 100.0) + mask_img = (np.clip(mask_img, 0.0, 1.0) * 255.0).astype(np.uint8) + + mask_image = 255.0 - mask_img # extract mask from alpha channel and invert + rgb_init_image = ( + 0.0 + new_img[:, :, 0:3] + ) # strip mask from init_img leaving only rgb channels + + hard_mask = np.zeros_like(cv2_img[:, :, 0]) + if top != 0: + hard_mask[0 : origin_h // 2, :] = 255 + if bottom != 0: + hard_mask[origin_h // 2 :, :] = 255 + if left != 0: + hard_mask[:, 0 : origin_w // 2] = 255 + if right != 0: + hard_mask[:, origin_w // 2 :] = 255 + + hard_mask = cv2.copyMakeBorder( + hard_mask, top, bottom, left, right, cv2.BORDER_DEFAULT, value=255 + ) + mask_image = np.where(hard_mask > 0, mask_image, 0) + return rgb_init_image.astype(np.uint8), mask_image.astype(np.uint8) + + +if __name__ == "__main__": + from pathlib import Path + + current_dir = Path(__file__).parent.absolute().resolve() + image_path = current_dir.parent / "tests" / "bunny.jpeg" + init_image = cv2.imread(str(image_path)) + init_image, mask_image = expand_image( + init_image, + top=100, + right=100, + bottom=100, + left=100, + softness=20, + space=20, + ) + print(mask_image.dtype, mask_image.min(), mask_image.max()) + print(init_image.dtype, init_image.min(), init_image.max()) + mask_image = mask_image.astype(np.uint8) + init_image = init_image.astype(np.uint8) + cv2.imwrite("expanded_image.png", init_image) + cv2.imwrite("expanded_mask.png", mask_image) diff --git a/py/iopaint/model/instruct_pix2pix.py b/py/iopaint/model/instruct_pix2pix.py new file mode 100644 index 0000000..fc8cd26 --- /dev/null +++ b/py/iopaint/model/instruct_pix2pix.py @@ -0,0 +1,64 @@ +import PIL.Image +import cv2 +import torch +from loguru import logger + +from iopaint.const import INSTRUCT_PIX2PIX_NAME +from .base import DiffusionInpaintModel +from iopaint.schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class InstructPix2Pix(DiffusionInpaintModel): + name = INSTRUCT_PIX2PIX_NAME + pad_mod = 8 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import StableDiffusionInstructPix2PixPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = {"local_files_only": is_local_files_only(**kwargs)} + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + self.model = StableDiffusionInstructPix2PixPipeline.from_pretrained( + self.name, variant="fp16", torch_dtype=torch_dtype, **model_kwargs + ) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + edit = pipe(prompt, image=image, num_inference_steps=20, image_guidance_scale=1.5, guidance_scale=7).images[0] + """ + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + num_inference_steps=config.sd_steps, + image_guidance_scale=config.p2p_image_guidance_scale, + guidance_scale=config.sd_guidance_scale, + output_type="np", + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/kandinsky.py b/py/iopaint/model/kandinsky.py new file mode 100644 index 0000000..1a0bf1c --- /dev/null +++ b/py/iopaint/model/kandinsky.py @@ -0,0 +1,65 @@ +import PIL.Image +import cv2 +import numpy as np +import torch + +from iopaint.const import KANDINSKY22_NAME +from .base import DiffusionInpaintModel +from iopaint.schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class Kandinsky(DiffusionInpaintModel): + pad_mod = 64 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import AutoPipelineForInpainting + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = { + "torch_dtype": torch_dtype, + "local_files_only": is_local_files_only(**kwargs), + } + self.model = AutoPipelineForInpainting.from_pretrained( + self.name, **model_kwargs + ).to(device) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + generator = torch.manual_seed(config.sd_seed) + mask = mask.astype(np.float32) / 255 + img_h, img_w = image.shape[:2] + + # kandinsky 没有 strength + output = self.model( + prompt=config.prompt, + negative_prompt=config.negative_prompt, + image=PIL.Image.fromarray(image), + mask_image=mask[:, :, 0], + height=img_h, + width=img_w, + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + generator=generator, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output + + +class Kandinsky22(Kandinsky): + name = KANDINSKY22_NAME diff --git a/py/iopaint/model/lama.py b/py/iopaint/model/lama.py new file mode 100644 index 0000000..7aba242 --- /dev/null +++ b/py/iopaint/model/lama.py @@ -0,0 +1,57 @@ +import os + +import cv2 +import numpy as np +import torch + +from iopaint.helper import ( + norm_img, + get_cache_path_by_url, + load_jit_model, + download_model, +) +from iopaint.schema import InpaintRequest +from .base import InpaintModel + +LAMA_MODEL_URL = os.environ.get( + "LAMA_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_big_lama/big-lama.pt", +) +LAMA_MODEL_MD5 = os.environ.get("LAMA_MODEL_MD5", "e3aa4aaa15225a33ec84f9f4bc47e500") + + +class LaMa(InpaintModel): + name = "lama" + pad_mod = 8 + is_erase_model = True + + @staticmethod + def download(): + download_model(LAMA_MODEL_URL, LAMA_MODEL_MD5) + + def init_model(self, device, **kwargs): + self.model = load_jit_model(LAMA_MODEL_URL, device, LAMA_MODEL_MD5).eval() + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(LAMA_MODEL_URL)) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W] + return: BGR IMAGE + """ + image = norm_img(image) + mask = norm_img(mask) + + mask = (mask > 0) * 1 + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + inpainted_image = self.model(image, mask) + + cur_res = inpainted_image[0].permute(1, 2, 0).detach().cpu().numpy() + cur_res = np.clip(cur_res * 255, 0, 255).astype("uint8") + cur_res = cv2.cvtColor(cur_res, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/ldm.py b/py/iopaint/model/ldm.py new file mode 100644 index 0000000..19e51a3 --- /dev/null +++ b/py/iopaint/model/ldm.py @@ -0,0 +1,336 @@ +import os + +import numpy as np +import torch +from loguru import logger + +from .base import InpaintModel +from .ddim_sampler import DDIMSampler +from .plms_sampler import PLMSSampler +from iopaint.schema import InpaintRequest, LDMSampler + +torch.manual_seed(42) +import torch.nn as nn +from iopaint.helper import ( + download_model, + norm_img, + get_cache_path_by_url, + load_jit_model, +) +from .utils import ( + make_beta_schedule, + timestep_embedding, +) + +LDM_ENCODE_MODEL_URL = os.environ.get( + "LDM_ENCODE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/cond_stage_model_encode.pt", +) +LDM_ENCODE_MODEL_MD5 = os.environ.get( + "LDM_ENCODE_MODEL_MD5", "23239fc9081956a3e70de56472b3f296" +) + +LDM_DECODE_MODEL_URL = os.environ.get( + "LDM_DECODE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/cond_stage_model_decode.pt", +) +LDM_DECODE_MODEL_MD5 = os.environ.get( + "LDM_DECODE_MODEL_MD5", "fe419cd15a750d37a4733589d0d3585c" +) + +LDM_DIFFUSION_MODEL_URL = os.environ.get( + "LDM_DIFFUSION_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_ldm/diffusion.pt", +) + +LDM_DIFFUSION_MODEL_MD5 = os.environ.get( + "LDM_DIFFUSION_MODEL_MD5", "b0afda12bf790c03aba2a7431f11d22d" +) + + +class DDPM(nn.Module): + # classic DDPM with Gaussian diffusion, in image space + def __init__( + self, + device, + timesteps=1000, + beta_schedule="linear", + linear_start=0.0015, + linear_end=0.0205, + cosine_s=0.008, + original_elbo_weight=0.0, + v_posterior=0.0, # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta + l_simple_weight=1.0, + parameterization="eps", # all assuming fixed variance schedules + use_positional_encodings=False, + ): + super().__init__() + self.device = device + self.parameterization = parameterization + self.use_positional_encodings = use_positional_encodings + + self.v_posterior = v_posterior + self.original_elbo_weight = original_elbo_weight + self.l_simple_weight = l_simple_weight + + self.register_schedule( + beta_schedule=beta_schedule, + timesteps=timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + betas = make_beta_schedule( + self.device, + beta_schedule, + timesteps, + linear_start=linear_start, + linear_end=linear_end, + cosine_s=cosine_s, + ) + alphas = 1.0 - betas + alphas_cumprod = np.cumprod(alphas, axis=0) + alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1]) + + (timesteps,) = betas.shape + self.num_timesteps = int(timesteps) + self.linear_start = linear_start + self.linear_end = linear_end + assert ( + alphas_cumprod.shape[0] == self.num_timesteps + ), "alphas have to be defined for each timestep" + + to_torch = lambda x: torch.tensor(x, dtype=torch.float32).to(self.device) + + self.register_buffer("betas", to_torch(betas)) + self.register_buffer("alphas_cumprod", to_torch(alphas_cumprod)) + self.register_buffer("alphas_cumprod_prev", to_torch(alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer("sqrt_alphas_cumprod", to_torch(np.sqrt(alphas_cumprod))) + self.register_buffer( + "sqrt_one_minus_alphas_cumprod", to_torch(np.sqrt(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "log_one_minus_alphas_cumprod", to_torch(np.log(1.0 - alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recip_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod)) + ) + self.register_buffer( + "sqrt_recipm1_alphas_cumprod", to_torch(np.sqrt(1.0 / alphas_cumprod - 1)) + ) + + # calculations for posterior q(x_{t-1} | x_t, x_0) + posterior_variance = (1 - self.v_posterior) * betas * ( + 1.0 - alphas_cumprod_prev + ) / (1.0 - alphas_cumprod) + self.v_posterior * betas + # above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t) + self.register_buffer("posterior_variance", to_torch(posterior_variance)) + # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain + self.register_buffer( + "posterior_log_variance_clipped", + to_torch(np.log(np.maximum(posterior_variance, 1e-20))), + ) + self.register_buffer( + "posterior_mean_coef1", + to_torch(betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)), + ) + self.register_buffer( + "posterior_mean_coef2", + to_torch( + (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod) + ), + ) + + if self.parameterization == "eps": + lvlb_weights = self.betas**2 / ( + 2 + * self.posterior_variance + * to_torch(alphas) + * (1 - self.alphas_cumprod) + ) + elif self.parameterization == "x0": + lvlb_weights = ( + 0.5 + * np.sqrt(torch.Tensor(alphas_cumprod)) + / (2.0 * 1 - torch.Tensor(alphas_cumprod)) + ) + else: + raise NotImplementedError("mu not supported") + # TODO how to choose this term + lvlb_weights[0] = lvlb_weights[1] + self.register_buffer("lvlb_weights", lvlb_weights, persistent=False) + assert not torch.isnan(self.lvlb_weights).all() + + +class LatentDiffusion(DDPM): + def __init__( + self, + diffusion_model, + device, + cond_stage_key="image", + cond_stage_trainable=False, + concat_mode=True, + scale_factor=1.0, + scale_by_std=False, + *args, + **kwargs, + ): + self.num_timesteps_cond = 1 + self.scale_by_std = scale_by_std + super().__init__(device, *args, **kwargs) + self.diffusion_model = diffusion_model + self.concat_mode = concat_mode + self.cond_stage_trainable = cond_stage_trainable + self.cond_stage_key = cond_stage_key + self.num_downs = 2 + self.scale_factor = scale_factor + + def make_cond_schedule( + self, + ): + self.cond_ids = torch.full( + size=(self.num_timesteps,), + fill_value=self.num_timesteps - 1, + dtype=torch.long, + ) + ids = torch.round( + torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond) + ).long() + self.cond_ids[: self.num_timesteps_cond] = ids + + def register_schedule( + self, + given_betas=None, + beta_schedule="linear", + timesteps=1000, + linear_start=1e-4, + linear_end=2e-2, + cosine_s=8e-3, + ): + super().register_schedule( + given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s + ) + + self.shorten_cond_schedule = self.num_timesteps_cond > 1 + if self.shorten_cond_schedule: + self.make_cond_schedule() + + def apply_model(self, x_noisy, t, cond): + # x_recon = self.model(x_noisy, t, cond['c_concat'][0]) # cond['c_concat'][0].shape 1,4,128,128 + t_emb = timestep_embedding(x_noisy.device, t, 256, repeat_only=False) + x_recon = self.diffusion_model(x_noisy, t_emb, cond) + return x_recon + + +class LDM(InpaintModel): + name = "ldm" + pad_mod = 32 + is_erase_model = True + + def __init__(self, device, fp16: bool = True, **kwargs): + self.fp16 = fp16 + super().__init__(device) + self.device = device + + def init_model(self, device, **kwargs): + self.diffusion_model = load_jit_model( + LDM_DIFFUSION_MODEL_URL, device, LDM_DIFFUSION_MODEL_MD5 + ) + self.cond_stage_model_decode = load_jit_model( + LDM_DECODE_MODEL_URL, device, LDM_DECODE_MODEL_MD5 + ) + self.cond_stage_model_encode = load_jit_model( + LDM_ENCODE_MODEL_URL, device, LDM_ENCODE_MODEL_MD5 + ) + if self.fp16 and "cuda" in str(device): + self.diffusion_model = self.diffusion_model.half() + self.cond_stage_model_decode = self.cond_stage_model_decode.half() + self.cond_stage_model_encode = self.cond_stage_model_encode.half() + + self.model = LatentDiffusion(self.diffusion_model, device) + + @staticmethod + def download(): + download_model(LDM_DIFFUSION_MODEL_URL, LDM_DIFFUSION_MODEL_MD5) + download_model(LDM_DECODE_MODEL_URL, LDM_DECODE_MODEL_MD5) + download_model(LDM_ENCODE_MODEL_URL, LDM_ENCODE_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(LDM_DIFFUSION_MODEL_URL), + get_cache_path_by_url(LDM_DECODE_MODEL_URL), + get_cache_path_by_url(LDM_ENCODE_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + @torch.cuda.amp.autocast() + def forward(self, image, mask, config: InpaintRequest): + """ + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + # image [1,3,512,512] float32 + # mask: [1,1,512,512] float32 + # masked_image: [1,3,512,512] float32 + if config.ldm_sampler == LDMSampler.ddim: + sampler = DDIMSampler(self.model) + elif config.ldm_sampler == LDMSampler.plms: + sampler = PLMSSampler(self.model) + else: + raise ValueError() + + steps = config.ldm_steps + image = norm_img(image) + mask = norm_img(mask) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + masked_image = (1 - mask) * image + + mask = self._norm(mask) + masked_image = self._norm(masked_image) + + c = self.cond_stage_model_encode(masked_image) + torch.cuda.empty_cache() + + cc = torch.nn.functional.interpolate(mask, size=c.shape[-2:]) # 1,1,128,128 + c = torch.cat((c, cc), dim=1) # 1,4,128,128 + + shape = (c.shape[1] - 1,) + c.shape[2:] + samples_ddim = sampler.sample( + steps=steps, conditioning=c, batch_size=c.shape[0], shape=shape + ) + torch.cuda.empty_cache() + x_samples_ddim = self.cond_stage_model_decode( + samples_ddim + ) # samples_ddim: 1, 3, 128, 128 float32 + torch.cuda.empty_cache() + + # image = torch.clamp((image + 1.0) / 2.0, min=0.0, max=1.0) + # mask = torch.clamp((mask + 1.0) / 2.0, min=0.0, max=1.0) + inpainted_image = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0) + + # inpainted = (1 - mask) * image + mask * predicted_image + inpainted_image = inpainted_image.cpu().numpy().transpose(0, 2, 3, 1)[0] * 255 + inpainted_image = inpainted_image.astype(np.uint8)[:, :, ::-1] + return inpainted_image + + def _norm(self, tensor): + return tensor * 2.0 - 1.0 diff --git a/py/iopaint/model/manga.py b/py/iopaint/model/manga.py new file mode 100644 index 0000000..1f58251 --- /dev/null +++ b/py/iopaint/model/manga.py @@ -0,0 +1,97 @@ +import os +import random + +import cv2 +import numpy as np +import torch +import time +from loguru import logger + +from iopaint.helper import get_cache_path_by_url, load_jit_model, download_model +from .base import InpaintModel +from iopaint.schema import InpaintRequest + + +MANGA_INPAINTOR_MODEL_URL = os.environ.get( + "MANGA_INPAINTOR_MODEL_URL", + "https://github.com/Sanster/models/releases/download/manga/manga_inpaintor.jit", +) +MANGA_INPAINTOR_MODEL_MD5 = os.environ.get( + "MANGA_INPAINTOR_MODEL_MD5", "7d8b269c4613b6b3768af714610da86c" +) + +MANGA_LINE_MODEL_URL = os.environ.get( + "MANGA_LINE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/manga/erika.jit", +) +MANGA_LINE_MODEL_MD5 = os.environ.get( + "MANGA_LINE_MODEL_MD5", "0c926d5a4af8450b0d00bc5b9a095644" +) + + +class Manga(InpaintModel): + name = "manga" + pad_mod = 16 + is_erase_model = True + + def init_model(self, device, **kwargs): + self.inpaintor_model = load_jit_model( + MANGA_INPAINTOR_MODEL_URL, device, MANGA_INPAINTOR_MODEL_MD5 + ) + self.line_model = load_jit_model( + MANGA_LINE_MODEL_URL, device, MANGA_LINE_MODEL_MD5 + ) + self.seed = 42 + + @staticmethod + def download(): + download_model(MANGA_INPAINTOR_MODEL_URL, MANGA_INPAINTOR_MODEL_MD5) + download_model(MANGA_LINE_MODEL_URL, MANGA_LINE_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(MANGA_INPAINTOR_MODEL_URL), + get_cache_path_by_url(MANGA_LINE_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + def forward(self, image, mask, config: InpaintRequest): + """ + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + seed = self.seed + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + gray_img = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) + gray_img = torch.from_numpy( + gray_img[np.newaxis, np.newaxis, :, :].astype(np.float32) + ).to(self.device) + start = time.time() + lines = self.line_model(gray_img) + torch.cuda.empty_cache() + lines = torch.clamp(lines, 0, 255) + logger.info(f"erika_model time: {time.time() - start}") + + mask = torch.from_numpy(mask[np.newaxis, :, :, :]).to(self.device) + mask = mask.permute(0, 3, 1, 2) + mask = torch.where(mask > 0.5, 1.0, 0.0) + noise = torch.randn_like(mask) + ones = torch.ones_like(mask) + + gray_img = gray_img / 255 * 2 - 1.0 + lines = lines / 255 * 2 - 1.0 + + start = time.time() + inpainted_image = self.inpaintor_model(gray_img, lines, mask, noise, ones) + logger.info(f"image_inpaintor_model time: {time.time() - start}") + + cur_res = inpainted_image[0].permute(1, 2, 0).detach().cpu().numpy() + cur_res = (cur_res * 127.5 + 127.5).astype(np.uint8) + cur_res = cv2.cvtColor(cur_res, cv2.COLOR_GRAY2BGR) + return cur_res diff --git a/py/iopaint/model/mat.py b/py/iopaint/model/mat.py new file mode 100644 index 0000000..0c5360f --- /dev/null +++ b/py/iopaint/model/mat.py @@ -0,0 +1,1945 @@ +import os +import random + +import cv2 +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint + +from iopaint.helper import ( + load_model, + get_cache_path_by_url, + norm_img, + download_model, +) +from iopaint.schema import InpaintRequest +from .base import InpaintModel +from .utils import ( + setup_filter, + Conv2dLayer, + FullyConnectedLayer, + conv2d_resample, + bias_act, + upsample2d, + activation_funcs, + MinibatchStdLayer, + to_2tuple, + normalize_2nd_moment, + set_seed, +) + + +class ModulatedConv2d(nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + style_dim, # dimension of the style code + demodulate=True, # perfrom demodulation + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + ): + super().__init__() + self.demodulate = demodulate + + self.weight = torch.nn.Parameter( + torch.randn([1, out_channels, in_channels, kernel_size, kernel_size]) + ) + self.out_channels = out_channels + self.kernel_size = kernel_size + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + self.padding = self.kernel_size // 2 + self.up = up + self.down = down + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + self.affine = FullyConnectedLayer(style_dim, in_channels, bias_init=1) + + def forward(self, x, style): + batch, in_channels, height, width = x.shape + style = self.affine(style).view(batch, 1, in_channels, 1, 1) + weight = self.weight * self.weight_gain * style + + if self.demodulate: + decoefs = (weight.pow(2).sum(dim=[2, 3, 4]) + 1e-8).rsqrt() + weight = weight * decoefs.view(batch, self.out_channels, 1, 1, 1) + + weight = weight.view( + batch * self.out_channels, in_channels, self.kernel_size, self.kernel_size + ) + x = x.view(1, batch * in_channels, height, width) + x = conv2d_resample( + x=x, + w=weight, + f=self.resample_filter, + up=self.up, + down=self.down, + padding=self.padding, + groups=batch, + ) + out = x.view(batch, self.out_channels, *x.shape[2:]) + + return out + + +class StyleConv(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + style_dim, # Intermediate latent (W) dimensionality. + resolution, # Resolution of this layer. + kernel_size=3, # Convolution kernel size. + up=1, # Integer upsampling factor. + use_noise=False, # Enable noise input? + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output of convolution layers to +-X, None = disable clamping. + demodulate=True, # perform demodulation + ): + super().__init__() + + self.conv = ModulatedConv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + up=up, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + ) + + self.use_noise = use_noise + self.resolution = resolution + if use_noise: + self.register_buffer("noise_const", torch.randn([resolution, resolution])) + self.noise_strength = torch.nn.Parameter(torch.zeros([])) + + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.activation = activation + self.act_gain = activation_funcs[activation].def_gain + self.conv_clamp = conv_clamp + + def forward(self, x, style, noise_mode="random", gain=1): + x = self.conv(x, style) + + assert noise_mode in ["random", "const", "none"] + + if self.use_noise: + if noise_mode == "random": + xh, xw = x.size()[-2:] + noise = ( + torch.randn([x.shape[0], 1, xh, xw], device=x.device) + * self.noise_strength + ) + if noise_mode == "const": + noise = self.noise_const * self.noise_strength + x = x + noise + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act( + x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp + ) + + return out + + +class ToRGB(torch.nn.Module): + def __init__( + self, + in_channels, + out_channels, + style_dim, + kernel_size=1, + resample_filter=[1, 3, 3, 1], + conv_clamp=None, + demodulate=False, + ): + super().__init__() + + self.conv = ModulatedConv2d( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + style_dim=style_dim, + demodulate=demodulate, + resample_filter=resample_filter, + conv_clamp=conv_clamp, + ) + self.bias = torch.nn.Parameter(torch.zeros([out_channels])) + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + + def forward(self, x, style, skip=None): + x = self.conv(x, style) + out = bias_act(x, self.bias, clamp=self.conv_clamp) + + if skip is not None: + if skip.shape != out.shape: + skip = upsample2d(skip, self.resample_filter) + out = out + skip + + return out + + +def get_style_code(a, b): + return torch.cat([a, b], dim=1) + + +class DecBlockFirst(nn.Module): + def __init__( + self, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.fc = FullyConnectedLayer( + in_features=in_channels * 2, + out_features=in_channels * 4**2, + activation=activation, + ) + self.conv = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlockFirstV2(nn.Module): + def __init__( + self, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=4, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[2] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): # res = 2, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode="random"): + style = get_style_code(ws[:, self.res * 2 - 5], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 4], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 3], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class MappingNet(torch.nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + num_ws, # Number of intermediate latents to output, None = do not broadcast. + num_layers=8, # Number of mapping layers. + embed_features=None, # Label embedding dimensionality, None = same as w_dim. + layer_features=None, # Number of intermediate features in the mapping layers, None = same as w_dim. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=0.01, # Learning rate multiplier for the mapping layers. + w_avg_beta=0.995, # Decay for tracking the moving average of W during training, None = do not track. + torch_dtype=torch.float32, + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.num_ws = num_ws + self.num_layers = num_layers + self.w_avg_beta = w_avg_beta + self.torch_dtype = torch_dtype + + if embed_features is None: + embed_features = w_dim + if c_dim == 0: + embed_features = 0 + if layer_features is None: + layer_features = w_dim + features_list = ( + [z_dim + embed_features] + [layer_features] * (num_layers - 1) + [w_dim] + ) + + if c_dim > 0: + self.embed = FullyConnectedLayer(c_dim, embed_features) + for idx in range(num_layers): + in_features = features_list[idx] + out_features = features_list[idx + 1] + layer = FullyConnectedLayer( + in_features, + out_features, + activation=activation, + lr_multiplier=lr_multiplier, + ) + setattr(self, f"fc{idx}", layer) + + if num_ws is not None and w_avg_beta is not None: + self.register_buffer("w_avg", torch.zeros([w_dim])) + + def forward( + self, z, c, truncation_psi=1, truncation_cutoff=None, skip_w_avg_update=False + ): + # Embed, normalize, and concat inputs. + x = None + if self.z_dim > 0: + x = normalize_2nd_moment(z) + if self.c_dim > 0: + y = normalize_2nd_moment(self.embed(c)) + x = torch.cat([x, y], dim=1) if x is not None else y + + # Main layers. + for idx in range(self.num_layers): + layer = getattr(self, f"fc{idx}") + x = layer(x) + + # Update moving average of W. + if self.w_avg_beta is not None and self.training and not skip_w_avg_update: + self.w_avg.copy_(x.detach().mean(dim=0).lerp(self.w_avg, self.w_avg_beta)) + + # Broadcast. + if self.num_ws is not None: + x = x.unsqueeze(1).repeat([1, self.num_ws, 1]) + + # Apply truncation. + if truncation_psi != 1: + assert self.w_avg_beta is not None + if self.num_ws is None or truncation_cutoff is None: + x = self.w_avg.lerp(x, truncation_psi) + else: + x[:, :truncation_cutoff] = self.w_avg.lerp( + x[:, :truncation_cutoff], truncation_psi + ) + + return x + + +class DisFromRGB(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + + def forward(self, x): + return self.conv(x) + + +class DisBlock(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + down=2, + activation=activation, + ) + self.skip = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + down=2, + bias=False, + ) + + def forward(self, x): + skip = self.skip(x, gain=np.sqrt(0.5)) + x = self.conv0(x) + x = self.conv1(x, gain=np.sqrt(0.5)) + out = skip + x + + return out + + +class Discriminator(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation="lrelu", + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + def nf(stage): + return np.clip( + int(channel_base / 2 ** (stage * channel_decay)), 1, channel_max + ) + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet( + z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None + ) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis.append( + Conv2dLayer( + nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation + ) + ) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + def forward(self, images_in, masks_in, c): + x = torch.cat([masks_in - 0.5, images_in], dim=1) + x = self.Dis(x) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + + return x + + +def nf(stage, channel_base=32768, channel_decay=1.0, channel_max=512): + NF = {512: 64, 256: 128, 128: 256, 64: 512, 32: 512, 16: 512, 8: 512, 4: 512} + return NF[2**stage] + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.fc1 = FullyConnectedLayer( + in_features=in_features, out_features=hidden_features, activation="lrelu" + ) + self.fc2 = FullyConnectedLayer( + in_features=hidden_features, out_features=out_features + ) + + def forward(self, x): + x = self.fc1(x) + x = self.fc2(x) + return x + + +def window_partition(x, window_size): + """ + Args: + x: (B, H, W, C) + window_size (int): window size + Returns: + windows: (num_windows*B, window_size, window_size, C) + """ + B, H, W, C = x.shape + x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows + + +def window_reverse(windows, window_size: int, H: int, W: int): + """ + Args: + windows: (num_windows*B, window_size, window_size, C) + window_size (int): Window size + H (int): Height of image + W (int): Width of image + Returns: + x: (B, H, W, C) + """ + B = int(windows.shape[0] / (H * W / window_size / window_size)) + # B = windows.shape[0] / (H * W / window_size / window_size) + x = windows.view( + B, H // window_size, W // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) + return x + + +class Conv2dLayerPartial(nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.conv = Conv2dLayer( + in_channels, + out_channels, + kernel_size, + bias, + activation, + up, + down, + resample_filter, + conv_clamp, + trainable, + ) + + self.weight_maskUpdater = torch.ones(1, 1, kernel_size, kernel_size) + self.slide_winsize = kernel_size**2 + self.stride = down + self.padding = kernel_size // 2 if kernel_size % 2 == 1 else 0 + + def forward(self, x, mask=None): + if mask is not None: + with torch.no_grad(): + if self.weight_maskUpdater.type() != x.type(): + self.weight_maskUpdater = self.weight_maskUpdater.to(x) + update_mask = F.conv2d( + mask, + self.weight_maskUpdater, + bias=None, + stride=self.stride, + padding=self.padding, + ) + mask_ratio = self.slide_winsize / (update_mask.to(torch.float32) + 1e-8) + update_mask = torch.clamp(update_mask, 0, 1) # 0 or 1 + mask_ratio = torch.mul(mask_ratio, update_mask).to(x.dtype) + x = self.conv(x) + x = torch.mul(x, mask_ratio) + return x, update_mask + else: + x = self.conv(x) + return x, None + + +class WindowAttention(nn.Module): + r"""Window based multi-head self attention (W-MSA) module with relative position bias. + It supports both of shifted and non-shifted window. + Args: + dim (int): Number of input channels. + window_size (tuple[int]): The height and width of the window. + num_heads (int): Number of attention heads. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set + attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0 + proj_drop (float, optional): Dropout ratio of output. Default: 0.0 + """ + + def __init__( + self, + dim, + window_size, + num_heads, + down_ratio=1, + qkv_bias=True, + qk_scale=None, + attn_drop=0.0, + proj_drop=0.0, + ): + super().__init__() + self.dim = dim + self.window_size = window_size # Wh, Ww + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = qk_scale or head_dim**-0.5 + + self.q = FullyConnectedLayer(in_features=dim, out_features=dim) + self.k = FullyConnectedLayer(in_features=dim, out_features=dim) + self.v = FullyConnectedLayer(in_features=dim, out_features=dim) + self.proj = FullyConnectedLayer(in_features=dim, out_features=dim) + + self.softmax = nn.Softmax(dim=-1) + + def forward(self, x, mask_windows=None, mask=None): + """ + Args: + x: input features with shape of (num_windows*B, N, C) + mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None + """ + B_, N, C = x.shape + norm_x = F.normalize(x, p=2.0, dim=-1, eps=torch.finfo(x.dtype).eps) + q = ( + self.q(norm_x) + .reshape(B_, N, self.num_heads, C // self.num_heads) + .permute(0, 2, 1, 3) + ) + k = ( + self.k(norm_x) + .view(B_, -1, self.num_heads, C // self.num_heads) + .permute(0, 2, 3, 1) + ) + v = ( + self.v(x) + .view(B_, -1, self.num_heads, C // self.num_heads) + .permute(0, 2, 1, 3) + ) + + attn = (q @ k) * self.scale + + if mask is not None: + nW = mask.shape[0] + attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze( + 1 + ).unsqueeze(0) + attn = attn.view(-1, self.num_heads, N, N) + + if mask_windows is not None: + attn_mask_windows = mask_windows.squeeze(-1).unsqueeze(1).unsqueeze(1) + attn = attn + attn_mask_windows.masked_fill( + attn_mask_windows == 0, float(-100.0) + ).masked_fill(attn_mask_windows == 1, float(0.0)) + with torch.no_grad(): + mask_windows = torch.clamp( + torch.sum(mask_windows, dim=1, keepdim=True), 0, 1 + ).repeat(1, N, 1) + + attn = self.softmax(attn) + x = (attn @ v).transpose(1, 2).reshape(B_, N, C) + x = self.proj(x) + return x, mask_windows + + +class SwinTransformerBlock(nn.Module): + r"""Swin Transformer Block. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resulotion. + num_heads (int): Number of attention heads. + window_size (int): Window size. + shift_size (int): Shift size for SW-MSA. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + act_layer (nn.Module, optional): Activation layer. Default: nn.GELU + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + """ + + def __init__( + self, + dim, + input_resolution, + num_heads, + down_ratio=1, + window_size=7, + shift_size=0, + mlp_ratio=4.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + act_layer=nn.GELU, + norm_layer=nn.LayerNorm, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + self.window_size = window_size + self.shift_size = shift_size + self.mlp_ratio = mlp_ratio + if min(self.input_resolution) <= self.window_size: + # if window size is larger than input resolution, we don't partition windows + self.shift_size = 0 + self.window_size = min(self.input_resolution) + assert ( + 0 <= self.shift_size < self.window_size + ), "shift_size must in 0-window_size" + + if self.shift_size > 0: + down_ratio = 1 + self.attn = WindowAttention( + dim, + window_size=to_2tuple(self.window_size), + num_heads=num_heads, + down_ratio=down_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + attn_drop=attn_drop, + proj_drop=drop, + ) + + self.fuse = FullyConnectedLayer( + in_features=dim * 2, out_features=dim, activation="lrelu" + ) + + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=act_layer, + drop=drop, + ) + + if self.shift_size > 0: + attn_mask = self.calculate_mask(self.input_resolution) + else: + attn_mask = None + + self.register_buffer("attn_mask", attn_mask) + + def calculate_mask(self, x_size): + # calculate attention mask for SW-MSA + H, W = x_size + img_mask = torch.zeros((1, H, W, 1)) # 1 H W 1 + h_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + w_slices = ( + slice(0, -self.window_size), + slice(-self.window_size, -self.shift_size), + slice(-self.shift_size, None), + ) + cnt = 0 + for h in h_slices: + for w in w_slices: + img_mask[:, h, w, :] = cnt + cnt += 1 + + mask_windows = window_partition( + img_mask, self.window_size + ) # nW, window_size, window_size, 1 + mask_windows = mask_windows.view(-1, self.window_size * self.window_size) + attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) + attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill( + attn_mask == 0, float(0.0) + ) + + return attn_mask + + def forward(self, x, x_size, mask=None): + # H, W = self.input_resolution + H, W = x_size + B, L, C = x.shape + # assert L == H * W, "input feature has wrong size" + + shortcut = x + x = x.view(B, H, W, C) + if mask is not None: + mask = mask.view(B, H, W, 1) + + # cyclic shift + if self.shift_size > 0: + shifted_x = torch.roll( + x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) + ) + if mask is not None: + shifted_mask = torch.roll( + mask, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2) + ) + else: + shifted_x = x + if mask is not None: + shifted_mask = mask + + # partition windows + x_windows = window_partition( + shifted_x, self.window_size + ) # nW*B, window_size, window_size, C + x_windows = x_windows.view( + -1, self.window_size * self.window_size, C + ) # nW*B, window_size*window_size, C + if mask is not None: + mask_windows = window_partition(shifted_mask, self.window_size) + mask_windows = mask_windows.view(-1, self.window_size * self.window_size, 1) + else: + mask_windows = None + + # W-MSA/SW-MSA (to be compatible for testing on images whose shapes are the multiple of window size + if self.input_resolution == x_size: + attn_windows, mask_windows = self.attn( + x_windows, mask_windows, mask=self.attn_mask + ) # nW*B, window_size*window_size, C + else: + attn_windows, mask_windows = self.attn( + x_windows, + mask_windows, + mask=self.calculate_mask(x_size).to(x.dtype).to(x.device), + ) # nW*B, window_size*window_size, C + + # merge windows + attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) + shifted_x = window_reverse(attn_windows, self.window_size, H, W) # B H' W' C + if mask is not None: + mask_windows = mask_windows.view(-1, self.window_size, self.window_size, 1) + shifted_mask = window_reverse(mask_windows, self.window_size, H, W) + + # reverse cyclic shift + if self.shift_size > 0: + x = torch.roll( + shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2) + ) + if mask is not None: + mask = torch.roll( + shifted_mask, shifts=(self.shift_size, self.shift_size), dims=(1, 2) + ) + else: + x = shifted_x + if mask is not None: + mask = shifted_mask + x = x.view(B, H * W, C) + if mask is not None: + mask = mask.view(B, H * W, 1) + + # FFN + x = self.fuse(torch.cat([shortcut, x], dim=-1)) + x = self.mlp(x) + + return x, mask + + +class PatchMerging(nn.Module): + def __init__(self, in_channels, out_channels, down=2): + super().__init__() + self.conv = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation="lrelu", + down=down, + ) + self.down = down + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.down != 1: + ratio = 1 / self.down + x_size = (int(x_size[0] * ratio), int(x_size[1] * ratio)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class PatchUpsampling(nn.Module): + def __init__(self, in_channels, out_channels, up=2): + super().__init__() + self.conv = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation="lrelu", + up=up, + ) + self.up = up + + def forward(self, x, x_size, mask=None): + x = token2feature(x, x_size) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(x, mask) + if self.up != 1: + x_size = (int(x_size[0] * self.up), int(x_size[1] * self.up)) + x = feature2token(x) + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class BasicLayer(nn.Module): + """A basic Swin Transformer layer for one stage. + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True + qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set. + drop (float, optional): Dropout rate. Default: 0.0 + attn_drop (float, optional): Attention dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + """ + + def __init__( + self, + dim, + input_resolution, + depth, + num_heads, + window_size, + down_ratio=1, + mlp_ratio=2.0, + qkv_bias=True, + qk_scale=None, + drop=0.0, + attn_drop=0.0, + drop_path=0.0, + norm_layer=nn.LayerNorm, + downsample=None, + use_checkpoint=False, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # patch merging layer + if downsample is not None: + # self.downsample = downsample(input_resolution, dim=dim, norm_layer=norm_layer) + self.downsample = downsample + else: + self.downsample = None + + # build blocks + self.blocks = nn.ModuleList( + [ + SwinTransformerBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + down_ratio=down_ratio, + window_size=window_size, + shift_size=0 if (i % 2 == 0) else window_size // 2, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + qk_scale=qk_scale, + drop=drop, + attn_drop=attn_drop, + drop_path=drop_path[i] + if isinstance(drop_path, list) + else drop_path, + norm_layer=norm_layer, + ) + for i in range(depth) + ] + ) + + self.conv = Conv2dLayerPartial( + in_channels=dim, out_channels=dim, kernel_size=3, activation="lrelu" + ) + + def forward(self, x, x_size, mask=None): + if self.downsample is not None: + x, x_size, mask = self.downsample(x, x_size, mask) + identity = x + for blk in self.blocks: + if self.use_checkpoint: + x, mask = checkpoint.checkpoint(blk, x, x_size, mask) + else: + x, mask = blk(x, x_size, mask) + if mask is not None: + mask = token2feature(mask, x_size) + x, mask = self.conv(token2feature(x, x_size), mask) + x = feature2token(x) + identity + if mask is not None: + mask = feature2token(mask) + return x, x_size, mask + + +class ToToken(nn.Module): + def __init__(self, in_channels=3, dim=128, kernel_size=5, stride=1): + super().__init__() + + self.proj = Conv2dLayerPartial( + in_channels=in_channels, + out_channels=dim, + kernel_size=kernel_size, + activation="lrelu", + ) + + def forward(self, x, mask): + x, mask = self.proj(x, mask) + + return x, mask + + +class EncFromRGB(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log2 + super().__init__() + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=1, + activation=activation, + ) + self.conv1 = Conv2dLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +class ConvBlockDown(nn.Module): + def __init__( + self, in_channels, out_channels, activation + ): # res = 2, ..., resolution_log + super().__init__() + + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + down=2, + ) + self.conv1 = Conv2dLayer( + in_channels=out_channels, + out_channels=out_channels, + kernel_size=3, + activation=activation, + ) + + def forward(self, x): + x = self.conv0(x) + x = self.conv1(x) + + return x + + +def token2feature(x, x_size): + B, N, C = x.shape + h, w = x_size + x = x.permute(0, 2, 1).reshape(B, C, h, w) + return x + + +def feature2token(x): + B, C, H, W = x.shape + x = x.view(B, C, -1).transpose(1, 2) + return x + + +class Encoder(nn.Module): + def __init__( + self, + res_log2, + img_channels, + activation, + patch_size=5, + channels=16, + drop_path_rate=0.1, + ): + super().__init__() + + self.resolution = [] + + for idx, i in enumerate(range(res_log2, 3, -1)): # from input size to 16x16 + res = 2**i + self.resolution.append(res) + if i == res_log2: + block = EncFromRGB(img_channels * 2 + 1, nf(i), activation) + else: + block = ConvBlockDown(nf(i + 1), nf(i), activation) + setattr(self, "EncConv_Block_%dx%d" % (res, res), block) + + def forward(self, x): + out = {} + for res in self.resolution: + res_log2 = int(np.log2(res)) + x = getattr(self, "EncConv_Block_%dx%d" % (res, res))(x) + out[res_log2] = x + + return out + + +class ToStyle(nn.Module): + def __init__(self, in_channels, out_channels, activation, drop_rate): + super().__init__() + self.conv = nn.Sequential( + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + down=2, + ), + ) + + self.pool = nn.AdaptiveAvgPool2d(1) + self.fc = FullyConnectedLayer( + in_features=in_channels, out_features=out_channels, activation=activation + ) + # self.dropout = nn.Dropout(drop_rate) + + def forward(self, x): + x = self.conv(x) + x = self.pool(x) + x = self.fc(x.flatten(start_dim=1)) + # x = self.dropout(x) + + return x + + +class DecBlockFirstV2(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.res = res + + self.conv0 = Conv2dLayer( + in_channels=in_channels, + out_channels=in_channels, + kernel_size=3, + activation=activation, + ) + self.conv1 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + # x = self.fc(x).view(x.shape[0], -1, 4, 4) + x = self.conv0(x) + x = x + E_features[self.res] + style = get_style_code(ws[:, 0], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, 1], gs) + img = self.toRGB(x, style, skip=None) + + return x, img + + +class DecBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): # res = 4, ..., resolution_log2 + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, ws, gs, E_features, noise_mode="random"): + style = get_style_code(ws[:, self.res * 2 - 9], gs) + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + E_features[self.res] + style = get_style_code(ws[:, self.res * 2 - 8], gs) + x = self.conv1(x, style, noise_mode=noise_mode) + style = get_style_code(ws[:, self.res * 2 - 7], gs) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class Decoder(nn.Module): + def __init__( + self, res_log2, activation, style_dim, use_noise, demodulate, img_channels + ): + super().__init__() + self.Dec_16x16 = DecBlockFirstV2( + 4, nf(4), nf(4), activation, style_dim, use_noise, demodulate, img_channels + ) + for res in range(5, res_log2 + 1): + setattr( + self, + "Dec_%dx%d" % (2**res, 2**res), + DecBlock( + res, + nf(res - 1), + nf(res), + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ), + ) + self.res_log2 = res_log2 + + def forward(self, x, ws, gs, E_features, noise_mode="random"): + x, img = self.Dec_16x16(x, ws, gs, E_features, noise_mode=noise_mode) + for res in range(5, self.res_log2 + 1): + block = getattr(self, "Dec_%dx%d" % (2**res, 2**res)) + x, img = block(x, img, ws, gs, E_features, noise_mode=noise_mode) + + return img + + +class DecStyleBlock(nn.Module): + def __init__( + self, + res, + in_channels, + out_channels, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ): + super().__init__() + self.res = res + + self.conv0 = StyleConv( + in_channels=in_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + up=2, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.conv1 = StyleConv( + in_channels=out_channels, + out_channels=out_channels, + style_dim=style_dim, + resolution=2**res, + kernel_size=3, + use_noise=use_noise, + activation=activation, + demodulate=demodulate, + ) + self.toRGB = ToRGB( + in_channels=out_channels, + out_channels=img_channels, + style_dim=style_dim, + kernel_size=1, + demodulate=False, + ) + + def forward(self, x, img, style, skip, noise_mode="random"): + x = self.conv0(x, style, noise_mode=noise_mode) + x = x + skip + x = self.conv1(x, style, noise_mode=noise_mode) + img = self.toRGB(x, style, skip=img) + + return x, img + + +class FirstStage(nn.Module): + def __init__( + self, + img_channels, + img_resolution=256, + dim=180, + w_dim=512, + use_noise=False, + demodulate=True, + activation="lrelu", + ): + super().__init__() + res = 64 + + self.conv_first = Conv2dLayerPartial( + in_channels=img_channels + 1, + out_channels=dim, + kernel_size=3, + activation=activation, + ) + self.enc_conv = nn.ModuleList() + down_time = int(np.log2(img_resolution // res)) + # 根据图片尺寸构建 swim transformer 的层数 + for i in range(down_time): # from input size to 64 + self.enc_conv.append( + Conv2dLayerPartial( + in_channels=dim, + out_channels=dim, + kernel_size=3, + down=2, + activation=activation, + ) + ) + + # from 64 -> 16 -> 64 + depths = [2, 3, 4, 3, 2] + ratios = [1, 1 / 2, 1 / 2, 2, 2] + num_heads = 6 + window_sizes = [8, 16, 16, 16, 8] + drop_path_rate = 0.1 + dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] + + self.tran = nn.ModuleList() + for i, depth in enumerate(depths): + res = int(res * ratios[i]) + if ratios[i] < 1: + merge = PatchMerging(dim, dim, down=int(1 / ratios[i])) + elif ratios[i] > 1: + merge = PatchUpsampling(dim, dim, up=ratios[i]) + else: + merge = None + self.tran.append( + BasicLayer( + dim=dim, + input_resolution=[res, res], + depth=depth, + num_heads=num_heads, + window_size=window_sizes[i], + drop_path=dpr[sum(depths[:i]) : sum(depths[: i + 1])], + downsample=merge, + ) + ) + + # global style + down_conv = [] + for i in range(int(np.log2(16))): + down_conv.append( + Conv2dLayer( + in_channels=dim, + out_channels=dim, + kernel_size=3, + down=2, + activation=activation, + ) + ) + down_conv.append(nn.AdaptiveAvgPool2d((1, 1))) + self.down_conv = nn.Sequential(*down_conv) + self.to_style = FullyConnectedLayer( + in_features=dim, out_features=dim * 2, activation=activation + ) + self.ws_style = FullyConnectedLayer( + in_features=w_dim, out_features=dim, activation=activation + ) + self.to_square = FullyConnectedLayer( + in_features=dim, out_features=16 * 16, activation=activation + ) + + style_dim = dim * 3 + self.dec_conv = nn.ModuleList() + for i in range(down_time): # from 64 to input size + res = res * 2 + self.dec_conv.append( + DecStyleBlock( + res, + dim, + dim, + activation, + style_dim, + use_noise, + demodulate, + img_channels, + ) + ) + + def forward(self, images_in, masks_in, ws, noise_mode="random"): + x = torch.cat([masks_in - 0.5, images_in * masks_in], dim=1) + + skips = [] + x, mask = self.conv_first(x, masks_in) # input size + skips.append(x) + for i, block in enumerate(self.enc_conv): # input size to 64 + x, mask = block(x, mask) + if i != len(self.enc_conv) - 1: + skips.append(x) + + x_size = x.size()[-2:] + x = feature2token(x) + mask = feature2token(mask) + mid = len(self.tran) // 2 + for i, block in enumerate(self.tran): # 64 to 16 + if i < mid: + x, x_size, mask = block(x, x_size, mask) + skips.append(x) + elif i > mid: + x, x_size, mask = block(x, x_size, None) + x = x + skips[mid - i] + else: + x, x_size, mask = block(x, x_size, None) + + mul_map = torch.ones_like(x) * 0.5 + mul_map = F.dropout(mul_map, training=True) + ws = self.ws_style(ws[:, -1]) + add_n = self.to_square(ws).unsqueeze(1) + add_n = ( + F.interpolate( + add_n, size=x.size(1), mode="linear", align_corners=False + ) + .squeeze(1) + .unsqueeze(-1) + ) + x = x * mul_map + add_n * (1 - mul_map) + gs = self.to_style( + self.down_conv(token2feature(x, x_size)).flatten(start_dim=1) + ) + style = torch.cat([gs, ws], dim=1) + + x = token2feature(x, x_size).contiguous() + img = None + for i, block in enumerate(self.dec_conv): + x, img = block( + x, img, style, skips[len(self.dec_conv) - i - 1], noise_mode=noise_mode + ) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + return img + + +class SynthesisNet(nn.Module): + def __init__( + self, + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # Output image resolution. + img_channels=3, # Number of color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_decay=1.0, + channel_max=512, # Maximum number of channels in any layer. + activation="lrelu", # Activation function: 'relu', 'lrelu', etc. + drop_rate=0.5, + use_noise=False, + demodulate=True, + ): + super().__init__() + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + + self.num_layers = resolution_log2 * 2 - 3 * 2 + self.img_resolution = img_resolution + self.resolution_log2 = resolution_log2 + + # first stage + self.first_stage = FirstStage( + img_channels, + img_resolution=img_resolution, + w_dim=w_dim, + use_noise=False, + demodulate=demodulate, + ) + + # second stage + self.enc = Encoder( + resolution_log2, img_channels, activation, patch_size=5, channels=16 + ) + self.to_square = FullyConnectedLayer( + in_features=w_dim, out_features=16 * 16, activation=activation + ) + self.to_style = ToStyle( + in_channels=nf(4), + out_channels=nf(2) * 2, + activation=activation, + drop_rate=drop_rate, + ) + style_dim = w_dim + nf(2) * 2 + self.dec = Decoder( + resolution_log2, activation, style_dim, use_noise, demodulate, img_channels + ) + + def forward(self, images_in, masks_in, ws, noise_mode="random", return_stg1=False): + out_stg1 = self.first_stage(images_in, masks_in, ws, noise_mode=noise_mode) + + # encoder + x = images_in * masks_in + out_stg1 * (1 - masks_in) + x = torch.cat([masks_in - 0.5, x, images_in * masks_in], dim=1) + E_features = self.enc(x) + + fea_16 = E_features[4] + mul_map = torch.ones_like(fea_16) * 0.5 + mul_map = F.dropout(mul_map, training=True) + add_n = self.to_square(ws[:, 0]).view(-1, 16, 16).unsqueeze(1) + add_n = F.interpolate( + add_n, size=fea_16.size()[-2:], mode="bilinear", align_corners=False + ) + fea_16 = fea_16 * mul_map + add_n * (1 - mul_map) + E_features[4] = fea_16 + + # style + gs = self.to_style(fea_16) + + # decoder + img = self.dec(fea_16, ws, gs, E_features, noise_mode=noise_mode) + + # ensemble + img = img * (1 - masks_in) + images_in * masks_in + + if not return_stg1: + return img + else: + return img, out_stg1 + + +class Generator(nn.Module): + def __init__( + self, + z_dim, # Input latent (Z) dimensionality, 0 = no latent. + c_dim, # Conditioning label (C) dimensionality, 0 = no label. + w_dim, # Intermediate latent (W) dimensionality. + img_resolution, # resolution of generated image + img_channels, # Number of input color channels. + synthesis_kwargs={}, # Arguments for SynthesisNetwork. + mapping_kwargs={}, # Arguments for MappingNetwork. + ): + super().__init__() + self.z_dim = z_dim + self.c_dim = c_dim + self.w_dim = w_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + self.synthesis = SynthesisNet( + w_dim=w_dim, + img_resolution=img_resolution, + img_channels=img_channels, + **synthesis_kwargs, + ) + self.mapping = MappingNet( + z_dim=z_dim, + c_dim=c_dim, + w_dim=w_dim, + num_ws=self.synthesis.num_layers, + **mapping_kwargs, + ) + + def forward( + self, + images_in, + masks_in, + z, + c, + truncation_psi=1, + truncation_cutoff=None, + skip_w_avg_update=False, + noise_mode="none", + return_stg1=False, + ): + ws = self.mapping( + z, + c, + truncation_psi=truncation_psi, + truncation_cutoff=truncation_cutoff, + skip_w_avg_update=skip_w_avg_update, + ) + img = self.synthesis(images_in, masks_in, ws, noise_mode=noise_mode) + return img + + +class Discriminator(torch.nn.Module): + def __init__( + self, + c_dim, # Conditioning label (C) dimensionality. + img_resolution, # Input resolution. + img_channels, # Number of input color channels. + channel_base=32768, # Overall multiplier for the number of channels. + channel_max=512, # Maximum number of channels in any layer. + channel_decay=1, + cmap_dim=None, # Dimensionality of mapped conditioning label, None = default. + activation="lrelu", + mbstd_group_size=4, # Group size for the minibatch standard deviation layer, None = entire minibatch. + mbstd_num_channels=1, # Number of features for the minibatch standard deviation layer, 0 = disable. + ): + super().__init__() + self.c_dim = c_dim + self.img_resolution = img_resolution + self.img_channels = img_channels + + resolution_log2 = int(np.log2(img_resolution)) + assert img_resolution == 2**resolution_log2 and img_resolution >= 4 + self.resolution_log2 = resolution_log2 + + if cmap_dim == None: + cmap_dim = nf(2) + if c_dim == 0: + cmap_dim = 0 + self.cmap_dim = cmap_dim + + if c_dim > 0: + self.mapping = MappingNet( + z_dim=0, c_dim=c_dim, w_dim=cmap_dim, num_ws=None, w_avg_beta=None + ) + + Dis = [DisFromRGB(img_channels + 1, nf(resolution_log2), activation)] + for res in range(resolution_log2, 2, -1): + Dis.append(DisBlock(nf(res), nf(res - 1), activation)) + + if mbstd_num_channels > 0: + Dis.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis.append( + Conv2dLayer( + nf(2) + mbstd_num_channels, nf(2), kernel_size=3, activation=activation + ) + ) + self.Dis = nn.Sequential(*Dis) + + self.fc0 = FullyConnectedLayer(nf(2) * 4**2, nf(2), activation=activation) + self.fc1 = FullyConnectedLayer(nf(2), 1 if cmap_dim == 0 else cmap_dim) + + # for 64x64 + Dis_stg1 = [DisFromRGB(img_channels + 1, nf(resolution_log2) // 2, activation)] + for res in range(resolution_log2, 2, -1): + Dis_stg1.append(DisBlock(nf(res) // 2, nf(res - 1) // 2, activation)) + + if mbstd_num_channels > 0: + Dis_stg1.append( + MinibatchStdLayer( + group_size=mbstd_group_size, num_channels=mbstd_num_channels + ) + ) + Dis_stg1.append( + Conv2dLayer( + nf(2) // 2 + mbstd_num_channels, + nf(2) // 2, + kernel_size=3, + activation=activation, + ) + ) + self.Dis_stg1 = nn.Sequential(*Dis_stg1) + + self.fc0_stg1 = FullyConnectedLayer( + nf(2) // 2 * 4**2, nf(2) // 2, activation=activation + ) + self.fc1_stg1 = FullyConnectedLayer( + nf(2) // 2, 1 if cmap_dim == 0 else cmap_dim + ) + + def forward(self, images_in, masks_in, images_stg1, c): + x = self.Dis(torch.cat([masks_in - 0.5, images_in], dim=1)) + x = self.fc1(self.fc0(x.flatten(start_dim=1))) + + x_stg1 = self.Dis_stg1(torch.cat([masks_in - 0.5, images_stg1], dim=1)) + x_stg1 = self.fc1_stg1(self.fc0_stg1(x_stg1.flatten(start_dim=1))) + + if self.c_dim > 0: + cmap = self.mapping(None, c) + + if self.cmap_dim > 0: + x = (x * cmap).sum(dim=1, keepdim=True) * (1 / np.sqrt(self.cmap_dim)) + x_stg1 = (x_stg1 * cmap).sum(dim=1, keepdim=True) * ( + 1 / np.sqrt(self.cmap_dim) + ) + + return x, x_stg1 + + +MAT_MODEL_URL = os.environ.get( + "MAT_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_mat/Places_512_FullData_G.pth", +) + +MAT_MODEL_MD5 = os.environ.get("MAT_MODEL_MD5", "8ca927835fa3f5e21d65ffcb165377ed") + + +class MAT(InpaintModel): + name = "mat" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + seed = 240 # pick up a random number + set_seed(seed) + + fp16 = not kwargs.get("no_half", False) + use_gpu = "cuda" in str(device) and torch.cuda.is_available() + self.torch_dtype = torch.float16 if use_gpu and fp16 else torch.float32 + + G = Generator( + z_dim=512, + c_dim=0, + w_dim=512, + img_resolution=512, + img_channels=3, + mapping_kwargs={"torch_dtype": self.torch_dtype}, + ).to(self.torch_dtype) + # fmt: off + self.model = load_model(G, MAT_MODEL_URL, device, MAT_MODEL_MD5) + self.z = torch.from_numpy(np.random.randn(1, G.z_dim)).to(self.torch_dtype).to(device) + self.label = torch.zeros([1, self.model.c_dim], device=device).to(self.torch_dtype) + # fmt: on + + @staticmethod + def download(): + download_model(MAT_MODEL_URL, MAT_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(MAT_MODEL_URL)) + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + + mask = (mask > 127) * 255 + mask = 255 - mask + mask = norm_img(mask) + + image = ( + torch.from_numpy(image).unsqueeze(0).to(self.torch_dtype).to(self.device) + ) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.torch_dtype).to(self.device) + + output = self.model( + image, mask, self.z, self.label, truncation_psi=1, noise_mode="none" + ) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/mi_gan.py b/py/iopaint/model/mi_gan.py new file mode 100644 index 0000000..f1ce25f --- /dev/null +++ b/py/iopaint/model/mi_gan.py @@ -0,0 +1,110 @@ +import os + +import cv2 +import torch + +from iopaint.helper import ( + load_jit_model, + download_model, + get_cache_path_by_url, + boxes_from_mask, + resize_max_size, + norm_img, +) +from .base import InpaintModel +from iopaint.schema import InpaintRequest + +MIGAN_MODEL_URL = os.environ.get( + "MIGAN_MODEL_URL", + "https://github.com/Sanster/models/releases/download/migan/migan_traced.pt", +) +MIGAN_MODEL_MD5 = os.environ.get("MIGAN_MODEL_MD5", "76eb3b1a71c400ee3290524f7a11b89c") + + +class MIGAN(InpaintModel): + name = "migan" + min_size = 512 + pad_mod = 512 + pad_to_square = True + is_erase_model = True + + def init_model(self, device, **kwargs): + self.model = load_jit_model(MIGAN_MODEL_URL, device, MIGAN_MODEL_MD5).eval() + + @staticmethod + def download(): + download_model(MIGAN_MODEL_URL, MIGAN_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + return os.path.exists(get_cache_path_by_url(MIGAN_MODEL_URL)) + + @torch.no_grad() + def __call__(self, image, mask, config: InpaintRequest): + """ + images: [H, W, C] RGB, not normalized + masks: [H, W] + return: BGR IMAGE + """ + if image.shape[0] == 512 and image.shape[1] == 512: + return self._pad_forward(image, mask, config) + + boxes = boxes_from_mask(mask) + crop_result = [] + config.hd_strategy_crop_margin = 128 + for box in boxes: + crop_image, crop_mask, crop_box = self._crop_box(image, mask, box, config) + origin_size = crop_image.shape[:2] + resize_image = resize_max_size(crop_image, size_limit=512) + resize_mask = resize_max_size(crop_mask, size_limit=512) + inpaint_result = self._pad_forward(resize_image, resize_mask, config) + + # only paste masked area result + inpaint_result = cv2.resize( + inpaint_result, + (origin_size[1], origin_size[0]), + interpolation=cv2.INTER_CUBIC, + ) + + original_pixel_indices = crop_mask < 127 + inpaint_result[original_pixel_indices] = crop_image[:, :, ::-1][ + original_pixel_indices + ] + + crop_result.append((inpaint_result, crop_box)) + + inpaint_result = image[:, :, ::-1].copy() + for crop_image, crop_box in crop_result: + x1, y1, x2, y2 = crop_box + inpaint_result[y1:y2, x1:x2, :] = crop_image + + return inpaint_result + + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] mask area == 255 + return: BGR IMAGE + """ + + image = norm_img(image) # [0, 1] + image = image * 2 - 1 # [0, 1] -> [-1, 1] + mask = (mask > 120) * 255 + mask = norm_img(mask) + + image = torch.from_numpy(image).unsqueeze(0).to(self.device) + mask = torch.from_numpy(mask).unsqueeze(0).to(self.device) + + erased_img = image * (1 - mask) + input_image = torch.cat([0.5 - mask, erased_img], dim=1) + + output = self.model(input_image) + output = ( + (output.permute(0, 2, 3, 1) * 127.5 + 127.5) + .round() + .clamp(0, 255) + .to(torch.uint8) + ) + output = output[0].cpu().numpy() + cur_res = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return cur_res diff --git a/py/iopaint/model/opencv2.py b/py/iopaint/model/opencv2.py new file mode 100644 index 0000000..de47209 --- /dev/null +++ b/py/iopaint/model/opencv2.py @@ -0,0 +1,29 @@ +import cv2 +from .base import InpaintModel +from iopaint.schema import InpaintRequest + +flag_map = {"INPAINT_NS": cv2.INPAINT_NS, "INPAINT_TELEA": cv2.INPAINT_TELEA} + + +class OpenCV2(InpaintModel): + name = "cv2" + pad_mod = 1 + is_erase_model = True + + @staticmethod + def is_downloaded() -> bool: + return True + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] + return: BGR IMAGE + """ + cur_res = cv2.inpaint( + image[:, :, ::-1], + mask, + inpaintRadius=config.cv2_radius, + flags=flag_map[config.cv2_flag], + ) + return cur_res diff --git a/py/iopaint/model/original_sd_configs/__init__.py b/py/iopaint/model/original_sd_configs/__init__.py new file mode 100644 index 0000000..23896a7 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/__init__.py @@ -0,0 +1,19 @@ +from pathlib import Path +from typing import Dict + +CURRENT_DIR = Path(__file__).parent.absolute() + + +def get_config_files() -> Dict[str, Path]: + """ + - `v1`: Config file for Stable Diffusion v1 + - `v2`: Config file for Stable Diffusion v2 + - `xl`: Config file for Stable Diffusion XL + - `xl_refiner`: Config file for Stable Diffusion XL Refiner + """ + return { + "v1": CURRENT_DIR / "v1-inference.yaml", + "v2": CURRENT_DIR / "v2-inference-v.yaml", + "xl": CURRENT_DIR / "sd_xl_base.yaml", + "xl_refiner": CURRENT_DIR / "sd_xl_refiner.yaml", + } diff --git a/py/iopaint/model/original_sd_configs/sd_xl_base.yaml b/py/iopaint/model/original_sd_configs/sd_xl_base.yaml new file mode 100644 index 0000000..6047379 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/sd_xl_base.yaml @@ -0,0 +1,93 @@ +model: + target: sgm.models.diffusion.DiffusionEngine + params: + scale_factor: 0.13025 + disable_first_stage_autocast: True + + denoiser_config: + target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser + params: + num_idx: 1000 + + scaling_config: + target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling + discretization_config: + target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization + + network_config: + target: sgm.modules.diffusionmodules.openaimodel.UNetModel + params: + adm_in_channels: 2816 + num_classes: sequential + use_checkpoint: True + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [4, 2] + num_res_blocks: 2 + channel_mult: [1, 2, 4] + num_head_channels: 64 + use_linear_in_transformer: True + transformer_depth: [1, 2, 10] + context_dim: 2048 + spatial_transformer_attn_type: softmax-xformers + + conditioner_config: + target: sgm.modules.GeneralConditioner + params: + emb_models: + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenCLIPEmbedder + params: + layer: hidden + layer_idx: 11 + + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2 + params: + arch: ViT-bigG-14 + version: laion2b_s39b_b160k + freeze: True + layer: penultimate + always_return_pooled: True + legacy: False + + - is_trainable: False + input_key: original_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: crop_coords_top_left + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: target_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + first_stage_config: + target: sgm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + attn_type: vanilla-xformers + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: [1, 2, 4, 4] + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity diff --git a/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml b/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml new file mode 100644 index 0000000..2d5ab44 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/sd_xl_refiner.yaml @@ -0,0 +1,86 @@ +model: + target: sgm.models.diffusion.DiffusionEngine + params: + scale_factor: 0.13025 + disable_first_stage_autocast: True + + denoiser_config: + target: sgm.modules.diffusionmodules.denoiser.DiscreteDenoiser + params: + num_idx: 1000 + + scaling_config: + target: sgm.modules.diffusionmodules.denoiser_scaling.EpsScaling + discretization_config: + target: sgm.modules.diffusionmodules.discretizer.LegacyDDPMDiscretization + + network_config: + target: sgm.modules.diffusionmodules.openaimodel.UNetModel + params: + adm_in_channels: 2560 + num_classes: sequential + use_checkpoint: True + in_channels: 4 + out_channels: 4 + model_channels: 384 + attention_resolutions: [4, 2] + num_res_blocks: 2 + channel_mult: [1, 2, 4, 4] + num_head_channels: 64 + use_linear_in_transformer: True + transformer_depth: 4 + context_dim: [1280, 1280, 1280, 1280] + spatial_transformer_attn_type: softmax-xformers + + conditioner_config: + target: sgm.modules.GeneralConditioner + params: + emb_models: + - is_trainable: False + input_key: txt + target: sgm.modules.encoders.modules.FrozenOpenCLIPEmbedder2 + params: + arch: ViT-bigG-14 + version: laion2b_s39b_b160k + legacy: False + freeze: True + layer: penultimate + always_return_pooled: True + + - is_trainable: False + input_key: original_size_as_tuple + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: crop_coords_top_left + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + - is_trainable: False + input_key: aesthetic_score + target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND + params: + outdim: 256 + + first_stage_config: + target: sgm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + attn_type: vanilla-xformers + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: [1, 2, 4, 4] + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity diff --git a/py/iopaint/model/original_sd_configs/v1-inference.yaml b/py/iopaint/model/original_sd_configs/v1-inference.yaml new file mode 100644 index 0000000..d4effe5 --- /dev/null +++ b/py/iopaint/model/original_sd_configs/v1-inference.yaml @@ -0,0 +1,70 @@ +model: + base_learning_rate: 1.0e-04 + target: ldm.models.diffusion.ddpm.LatentDiffusion + params: + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false # Note: different from the one we trained before + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False + + scheduler_config: # 10000 warmup steps + target: ldm.lr_scheduler.LambdaLinearScheduler + params: + warm_up_steps: [ 10000 ] + cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases + f_start: [ 1.e-6 ] + f_max: [ 1. ] + f_min: [ 1. ] + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_heads: 8 + use_spatial_transformer: True + transformer_depth: 1 + context_dim: 768 + use_checkpoint: True + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenCLIPEmbedder diff --git a/py/iopaint/model/original_sd_configs/v2-inference-v.yaml b/py/iopaint/model/original_sd_configs/v2-inference-v.yaml new file mode 100644 index 0000000..8ec8dfb --- /dev/null +++ b/py/iopaint/model/original_sd_configs/v2-inference-v.yaml @@ -0,0 +1,68 @@ +model: + base_learning_rate: 1.0e-4 + target: ldm.models.diffusion.ddpm.LatentDiffusion + params: + parameterization: "v" + linear_start: 0.00085 + linear_end: 0.0120 + num_timesteps_cond: 1 + log_every_t: 200 + timesteps: 1000 + first_stage_key: "jpg" + cond_stage_key: "txt" + image_size: 64 + channels: 4 + cond_stage_trainable: false + conditioning_key: crossattn + monitor: val/loss_simple_ema + scale_factor: 0.18215 + use_ema: False # we set this to false because this is an inference only config + + unet_config: + target: ldm.modules.diffusionmodules.openaimodel.UNetModel + params: + use_checkpoint: True + use_fp16: True + image_size: 32 # unused + in_channels: 4 + out_channels: 4 + model_channels: 320 + attention_resolutions: [ 4, 2, 1 ] + num_res_blocks: 2 + channel_mult: [ 1, 2, 4, 4 ] + num_head_channels: 64 # need to fix for flash-attn + use_spatial_transformer: True + use_linear_in_transformer: True + transformer_depth: 1 + context_dim: 1024 + legacy: False + + first_stage_config: + target: ldm.models.autoencoder.AutoencoderKL + params: + embed_dim: 4 + monitor: val/rec_loss + ddconfig: + #attn_type: "vanilla-xformers" + double_z: true + z_channels: 4 + resolution: 256 + in_channels: 3 + out_ch: 3 + ch: 128 + ch_mult: + - 1 + - 2 + - 4 + - 4 + num_res_blocks: 2 + attn_resolutions: [] + dropout: 0.0 + lossconfig: + target: torch.nn.Identity + + cond_stage_config: + target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder + params: + freeze: True + layer: "penultimate" diff --git a/py/iopaint/model/paint_by_example.py b/py/iopaint/model/paint_by_example.py new file mode 100644 index 0000000..bf1e5b7 --- /dev/null +++ b/py/iopaint/model/paint_by_example.py @@ -0,0 +1,68 @@ +import PIL +import PIL.Image +import cv2 +import torch +from loguru import logger + +from iopaint.helper import decode_base64_to_image +from .base import DiffusionInpaintModel +from iopaint.schema import InpaintRequest +from .utils import get_torch_dtype, enable_low_mem, is_local_files_only + + +class PaintByExample(DiffusionInpaintModel): + name = "Fantasy-Studio/Paint-by-Example" + pad_mod = 8 + min_size = 512 + + def init_model(self, device: torch.device, **kwargs): + from diffusers import DiffusionPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + model_kwargs = { + "local_files_only": is_local_files_only(**kwargs), + } + + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Paint By Example Model NSFW checker") + model_kwargs.update( + dict(safety_checker=None, requires_safety_checker=False) + ) + + self.model = DiffusionPipeline.from_pretrained( + self.name, torch_dtype=torch_dtype, **model_kwargs + ) + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + # TODO: gpu_id + if kwargs.get("cpu_offload", False) and use_gpu: + self.model.image_encoder = self.model.image_encoder.to(device) + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + if config.paint_by_example_example_image is None: + raise ValueError("paint_by_example_example_image is required") + example_image, _, _ = decode_base64_to_image( + config.paint_by_example_example_image + ) + output = self.model( + image=PIL.Image.fromarray(image), + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + example_image=PIL.Image.fromarray(example_image), + num_inference_steps=config.sd_steps, + guidance_scale=config.sd_guidance_scale, + negative_prompt="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature", + output_type="np.array", + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/plms_sampler.py b/py/iopaint/model/plms_sampler.py new file mode 100644 index 0000000..131a8f4 --- /dev/null +++ b/py/iopaint/model/plms_sampler.py @@ -0,0 +1,225 @@ +# From: https://github.com/CompVis/latent-diffusion/blob/main/ldm/models/diffusion/plms.py +import torch +import numpy as np +from .utils import make_ddim_timesteps, make_ddim_sampling_parameters, noise_like +from tqdm import tqdm + + +class PLMSSampler(object): + def __init__(self, model, schedule="linear", **kwargs): + super().__init__() + self.model = model + self.ddpm_num_timesteps = model.num_timesteps + self.schedule = schedule + + def register_buffer(self, name, attr): + setattr(self, name, attr) + + def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True): + if ddim_eta != 0: + raise ValueError('ddim_eta must be 0 for PLMS') + self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps, + num_ddpm_timesteps=self.ddpm_num_timesteps, verbose=verbose) + alphas_cumprod = self.model.alphas_cumprod + assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep' + to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device) + + self.register_buffer('betas', to_torch(self.model.betas)) + self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod)) + self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev)) + + # calculations for diffusion q(x_t | x_{t-1}) and others + self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu()))) + self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu()))) + self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu()))) + self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1))) + + # ddim sampling parameters + ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(), + ddim_timesteps=self.ddim_timesteps, + eta=ddim_eta, verbose=verbose) + self.register_buffer('ddim_sigmas', ddim_sigmas) + self.register_buffer('ddim_alphas', ddim_alphas) + self.register_buffer('ddim_alphas_prev', ddim_alphas_prev) + self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas)) + sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt( + (1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * ( + 1 - self.alphas_cumprod / self.alphas_cumprod_prev)) + self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps) + + @torch.no_grad() + def sample(self, + steps, + batch_size, + shape, + conditioning=None, + callback=None, + normals_sequence=None, + img_callback=None, + quantize_x0=False, + eta=0., + mask=None, + x0=None, + temperature=1., + noise_dropout=0., + score_corrector=None, + corrector_kwargs=None, + verbose=False, + x_T=None, + log_every_t=100, + unconditional_guidance_scale=1., + unconditional_conditioning=None, + # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ... + **kwargs + ): + if conditioning is not None: + if isinstance(conditioning, dict): + cbs = conditioning[list(conditioning.keys())[0]].shape[0] + if cbs != batch_size: + print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}") + else: + if conditioning.shape[0] != batch_size: + print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}") + + self.make_schedule(ddim_num_steps=steps, ddim_eta=eta, verbose=verbose) + # sampling + C, H, W = shape + size = (batch_size, C, H, W) + print(f'Data shape for PLMS sampling is {size}') + + samples = self.plms_sampling(conditioning, size, + callback=callback, + img_callback=img_callback, + quantize_denoised=quantize_x0, + mask=mask, x0=x0, + ddim_use_original_steps=False, + noise_dropout=noise_dropout, + temperature=temperature, + score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + x_T=x_T, + log_every_t=log_every_t, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + ) + return samples + + @torch.no_grad() + def plms_sampling(self, cond, shape, + x_T=None, ddim_use_original_steps=False, + callback=None, timesteps=None, quantize_denoised=False, + mask=None, x0=None, img_callback=None, log_every_t=100, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, ): + device = self.model.betas.device + b = shape[0] + if x_T is None: + img = torch.randn(shape, device=device) + else: + img = x_T + + if timesteps is None: + timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps + elif timesteps is not None and not ddim_use_original_steps: + subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1 + timesteps = self.ddim_timesteps[:subset_end] + + time_range = list(reversed(range(0, timesteps))) if ddim_use_original_steps else np.flip(timesteps) + total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0] + print(f"Running PLMS Sampling with {total_steps} timesteps") + + iterator = tqdm(time_range, desc='PLMS Sampler', total=total_steps) + old_eps = [] + + for i, step in enumerate(iterator): + index = total_steps - i - 1 + ts = torch.full((b,), step, device=device, dtype=torch.long) + ts_next = torch.full((b,), time_range[min(i + 1, len(time_range) - 1)], device=device, dtype=torch.long) + + if mask is not None: + assert x0 is not None + img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass? + img = img_orig * mask + (1. - mask) * img + + outs = self.p_sample_plms(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps, + quantize_denoised=quantize_denoised, temperature=temperature, + noise_dropout=noise_dropout, score_corrector=score_corrector, + corrector_kwargs=corrector_kwargs, + unconditional_guidance_scale=unconditional_guidance_scale, + unconditional_conditioning=unconditional_conditioning, + old_eps=old_eps, t_next=ts_next) + img, pred_x0, e_t = outs + old_eps.append(e_t) + if len(old_eps) >= 4: + old_eps.pop(0) + if callback: callback(i) + if img_callback: img_callback(pred_x0, i) + + return img + + @torch.no_grad() + def p_sample_plms(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False, + temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None, + unconditional_guidance_scale=1., unconditional_conditioning=None, old_eps=None, t_next=None): + b, *_, device = *x.shape, x.device + + def get_model_output(x, t): + if unconditional_conditioning is None or unconditional_guidance_scale == 1.: + e_t = self.model.apply_model(x, t, c) + else: + x_in = torch.cat([x] * 2) + t_in = torch.cat([t] * 2) + c_in = torch.cat([unconditional_conditioning, c]) + e_t_uncond, e_t = self.model.apply_model(x_in, t_in, c_in).chunk(2) + e_t = e_t_uncond + unconditional_guidance_scale * (e_t - e_t_uncond) + + if score_corrector is not None: + assert self.model.parameterization == "eps" + e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs) + + return e_t + + alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas + alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev + sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas + sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas + + def get_x_prev_and_pred_x0(e_t, index): + # select parameters corresponding to the currently considered timestep + a_t = torch.full((b, 1, 1, 1), alphas[index], device=device) + a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device) + sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device) + sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index], device=device) + + # current prediction for x_0 + pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt() + if quantize_denoised: + pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0) + # direction pointing to x_t + dir_xt = (1. - a_prev - sigma_t ** 2).sqrt() * e_t + noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature + if noise_dropout > 0.: + noise = torch.nn.functional.dropout(noise, p=noise_dropout) + x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise + return x_prev, pred_x0 + + e_t = get_model_output(x, t) + if len(old_eps) == 0: + # Pseudo Improved Euler (2nd order) + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t, index) + e_t_next = get_model_output(x_prev, t_next) + e_t_prime = (e_t + e_t_next) / 2 + elif len(old_eps) == 1: + # 2nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (3 * e_t - old_eps[-1]) / 2 + elif len(old_eps) == 2: + # 3nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (23 * e_t - 16 * old_eps[-1] + 5 * old_eps[-2]) / 12 + elif len(old_eps) >= 3: + # 4nd order Pseudo Linear Multistep (Adams-Bashforth) + e_t_prime = (55 * e_t - 59 * old_eps[-1] + 37 * old_eps[-2] - 9 * old_eps[-3]) / 24 + + x_prev, pred_x0 = get_x_prev_and_pred_x0(e_t_prime, index) + + return x_prev, pred_x0, e_t diff --git a/py/iopaint/model/power_paint/__init__.py b/py/iopaint/model/power_paint/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/model/power_paint/pipeline_powerpaint.py b/py/iopaint/model/power_paint/pipeline_powerpaint.py new file mode 100644 index 0000000..13c1d27 --- /dev/null +++ b/py/iopaint/model/power_paint/pipeline_powerpaint.py @@ -0,0 +1,1243 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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. + +import inspect +from typing import Any, Callable, Dict, List, Optional, Union + +import numpy as np +import PIL +import torch +from packaging import version +from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer +from diffusers.configuration_utils import FrozenDict +from diffusers.image_processor import VaeImageProcessor +from diffusers.loaders import ( + FromSingleFileMixin, + LoraLoaderMixin, + TextualInversionLoaderMixin, +) +from diffusers.models import ( + AsymmetricAutoencoderKL, + AutoencoderKL, + UNet2DConditionModel, +) +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import ( + deprecate, + is_accelerate_available, + is_accelerate_version, + logging, +) +from diffusers.utils.torch_utils import randn_tensor +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import ( + StableDiffusionSafetyChecker, +) + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +def prepare_mask_and_masked_image( + image, mask, height, width, return_image: bool = False +): + """ + Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be + converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the + ``image`` and ``1`` for the ``mask``. + + The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be + binarized (``mask > 0.5``) and cast to ``torch.float32`` too. + + Args: + image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint. + It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width`` + ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``. + mask (_type_): The mask to apply to the image, i.e. regions to inpaint. + It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width`` + ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``. + + + Raises: + ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask + should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions. + TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not + (ot the other way around). + + Returns: + tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4 + dimensions: ``batch x channels x height x width``. + """ + + if image is None: + raise ValueError("`image` input cannot be undefined.") + + if mask is None: + raise ValueError("`mask_image` input cannot be undefined.") + + if isinstance(image, torch.Tensor): + if not isinstance(mask, torch.Tensor): + raise TypeError( + f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not" + ) + + # Batch single image + if image.ndim == 3: + assert ( + image.shape[0] == 3 + ), "Image outside a batch should be of shape (3, H, W)" + image = image.unsqueeze(0) + + # Batch and add channel dim for single mask + if mask.ndim == 2: + mask = mask.unsqueeze(0).unsqueeze(0) + + # Batch single mask or add channel dim + if mask.ndim == 3: + # Single batched mask, no channel dim or single mask not batched but channel dim + if mask.shape[0] == 1: + mask = mask.unsqueeze(0) + + # Batched masks no channel dim + else: + mask = mask.unsqueeze(1) + + assert ( + image.ndim == 4 and mask.ndim == 4 + ), "Image and Mask must have 4 dimensions" + assert ( + image.shape[-2:] == mask.shape[-2:] + ), "Image and Mask must have the same spatial dimensions" + assert ( + image.shape[0] == mask.shape[0] + ), "Image and Mask must have the same batch size" + + # Check image is in [-1, 1] + if image.min() < -1 or image.max() > 1: + raise ValueError("Image should be in [-1, 1] range") + + # Check mask is in [0, 1] + if mask.min() < 0 or mask.max() > 1: + raise ValueError("Mask should be in [0, 1] range") + + # Binarize mask + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + # Image as float32 + image = image.to(dtype=torch.float32) + elif isinstance(mask, torch.Tensor): + raise TypeError( + f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not" + ) + else: + # preprocess image + if isinstance(image, (PIL.Image.Image, np.ndarray)): + image = [image] + if isinstance(image, list) and isinstance(image[0], PIL.Image.Image): + # resize all images w.r.t passed height an width + image = [ + i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image + ] + image = [np.array(i.convert("RGB"))[None, :] for i in image] + image = np.concatenate(image, axis=0) + elif isinstance(image, list) and isinstance(image[0], np.ndarray): + image = np.concatenate([i[None, :] for i in image], axis=0) + + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 + + # preprocess mask + if isinstance(mask, (PIL.Image.Image, np.ndarray)): + mask = [mask] + + if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image): + mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask] + mask = np.concatenate( + [np.array(m.convert("L"))[None, None, :] for m in mask], axis=0 + ) + mask = mask.astype(np.float32) / 255.0 + elif isinstance(mask, list) and isinstance(mask[0], np.ndarray): + mask = np.concatenate([m[None, None, :] for m in mask], axis=0) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + mask = torch.from_numpy(mask) + + masked_image = image * (mask < 0.5) + + # n.b. ensure backwards compatibility as old function does not return image + if return_image: + return mask, masked_image, image + + return mask, masked_image + + +class StableDiffusionInpaintPipeline( + DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin +): + r""" + Pipeline for text-guided image inpainting using Stable Diffusion. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods + implemented for all pipelines (downloading, saving, running on a particular device, etc.). + + The pipeline also inherits the following loading methods: + - [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings + - [`~loaders.LoraLoaderMixin.load_lora_weights`] for loading LoRA weights + - [`~loaders.LoraLoaderMixin.save_lora_weights`] for saving LoRA weights + + Args: + vae ([`AutoencoderKL`, `AsymmetricAutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)). + tokenizer ([`~transformers.CLIPTokenizer`]): + A `CLIPTokenizer` to tokenize text. + unet ([`UNet2DConditionModel`]): + A `UNet2DConditionModel` to denoise the encoded image latents. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for more details + about a model's potential harms. + feature_extractor ([`~transformers.CLIPImageProcessor`]): + A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`. + """ + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae: Union[AutoencoderKL, AsymmetricAutoencoderKL], + text_encoder: CLIPTextModel, + tokenizer: CLIPTokenizer, + unet: UNet2DConditionModel, + scheduler: KarrasDiffusionSchedulers, + safety_checker: StableDiffusionSafetyChecker, + feature_extractor: CLIPImageProcessor, + requires_safety_checker: bool = True, + ): + super().__init__() + + if ( + hasattr(scheduler.config, "steps_offset") + and scheduler.config.steps_offset != 1 + ): + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`" + f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure " + "to update the config accordingly as leaving `steps_offset` might led to incorrect results" + " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," + " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" + " file" + ) + deprecate( + "steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False + ) + new_config = dict(scheduler.config) + new_config["steps_offset"] = 1 + scheduler._internal_dict = FrozenDict(new_config) + + if ( + hasattr(scheduler.config, "skip_prk_steps") + and scheduler.config.skip_prk_steps is False + ): + deprecation_message = ( + f"The configuration file of this scheduler: {scheduler} has not set the configuration" + " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" + " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" + " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" + " Hub, it would be very nice if you could open a Pull request for the" + " `scheduler/scheduler_config.json` file" + ) + deprecate( + "skip_prk_steps not set", + "1.0.0", + deprecation_message, + standard_warn=False, + ) + new_config = dict(scheduler.config) + new_config["skip_prk_steps"] = True + scheduler._internal_dict = FrozenDict(new_config) + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + is_unet_version_less_0_9_0 = hasattr( + unet.config, "_diffusers_version" + ) and version.parse( + version.parse(unet.config._diffusers_version).base_version + ) < version.parse( + "0.9.0.dev0" + ) + is_unet_sample_size_less_64 = ( + hasattr(unet.config, "sample_size") and unet.config.sample_size < 64 + ) + if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64: + deprecation_message = ( + "The configuration file of the unet has set the default `sample_size` to smaller than" + " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the" + " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-" + " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5" + " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the" + " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`" + " in the config might lead to incorrect results in future versions. If you have downloaded this" + " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for" + " the `unet/config.json` file" + ) + deprecate( + "sample_size<64", "1.0.0", deprecation_message, standard_warn=False + ) + new_config = dict(unet.config) + new_config["sample_size"] = 64 + unet._internal_dict = FrozenDict(new_config) + + # Check shapes, assume num_channels_latents == 4, num_channels_mask == 1, num_channels_masked == 4 + if unet.config.in_channels != 9: + logger.info( + f"You have loaded a UNet with {unet.config.in_channels} input channels which." + ) + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_model_cpu_offload + def enable_model_cpu_offload(self, gpu_id=0): + r""" + Offload all models to CPU to reduce memory usage with a low impact on performance. Moves one whole model at a + time to the GPU when its `forward` method is called, and the model remains in GPU until the next model runs. + Memory savings are lower than using `enable_sequential_cpu_offload`, but performance is much better due to the + iterative execution of the `unet`. + """ + if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"): + from accelerate import cpu_offload_with_hook + else: + raise ImportError( + "`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher." + ) + + device = torch.device(f"cuda:{gpu_id}") + + if self.device.type != "cpu": + self.to("cpu", silence_dtype_warnings=True) + torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) + + hook = None + for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]: + _, hook = cpu_offload_with_hook( + cpu_offloaded_model, device, prev_module_hook=hook + ) + + if self.safety_checker is not None: + _, hook = cpu_offload_with_hook( + self.safety_checker, device, prev_module_hook=hook + ) + + # We'll offload the last model manually. + self.final_offload_hook = hook + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt + def _encode_prompt( + self, + promptA, + promptB, + t, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA=None, + negative_promptB=None, + t_nag=None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + lora_scale: Optional[float] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + lora_scale (`float`, *optional*): + A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. + """ + # set lora scale so that monkey patched LoRA + # function of text encoder can correctly access it + if lora_scale is not None and isinstance(self, LoraLoaderMixin): + self._lora_scale = lora_scale + + prompt = promptA + negative_prompt = negative_promptA + + if promptA is not None and isinstance(promptA, str): + batch_size = 1 + elif promptA is not None and isinstance(promptA, list): + batch_size = len(promptA) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + promptA = self.maybe_convert_prompt(promptA, self.tokenizer) + + text_inputsA = self.tokenizer( + promptA, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_inputsB = self.tokenizer( + promptB, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_input_idsA = text_inputsA.input_ids + text_input_idsB = text_inputsB.input_ids + untruncated_ids = self.tokenizer( + promptA, padding="longest", return_tensors="pt" + ).input_ids + + if untruncated_ids.shape[-1] >= text_input_idsA.shape[ + -1 + ] and not torch.equal(text_input_idsA, untruncated_ids): + removed_text = self.tokenizer.batch_decode( + untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] + ) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + if ( + hasattr(self.text_encoder.config, "use_attention_mask") + and self.text_encoder.config.use_attention_mask + ): + attention_mask = text_inputsA.attention_mask.to(device) + else: + attention_mask = None + + # print("text_input_idsA: ",text_input_idsA) + # print("text_input_idsB: ",text_input_idsB) + # print('t: ',t) + + prompt_embedsA = self.text_encoder( + text_input_idsA.to(device), + attention_mask=attention_mask, + ) + prompt_embedsA = prompt_embedsA[0] + + prompt_embedsB = self.text_encoder( + text_input_idsB.to(device), + attention_mask=attention_mask, + ) + prompt_embedsB = prompt_embedsB[0] + prompt_embeds = prompt_embedsA * (t) + (1 - t) * prompt_embedsB + # print("prompt_embeds: ",prompt_embeds) + + if self.text_encoder is not None: + prompt_embeds_dtype = self.text_encoder.dtype + elif self.unet is not None: + prompt_embeds_dtype = self.unet.dtype + else: + prompt_embeds_dtype = prompt_embeds.dtype + + prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view( + bs_embed * num_images_per_prompt, seq_len, -1 + ) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance and negative_prompt_embeds is None: + uncond_tokensA: List[str] + uncond_tokensB: List[str] + if negative_prompt is None: + uncond_tokensA = [""] * batch_size + uncond_tokensB = [""] * batch_size + elif prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokensA = [negative_promptA] + uncond_tokensB = [negative_promptB] + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokensA = negative_promptA + uncond_tokensB = negative_promptB + + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + uncond_tokensA = self.maybe_convert_prompt( + uncond_tokensA, self.tokenizer + ) + uncond_tokensB = self.maybe_convert_prompt( + uncond_tokensB, self.tokenizer + ) + + max_length = prompt_embeds.shape[1] + uncond_inputA = self.tokenizer( + uncond_tokensA, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + uncond_inputB = self.tokenizer( + uncond_tokensB, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + if ( + hasattr(self.text_encoder.config, "use_attention_mask") + and self.text_encoder.config.use_attention_mask + ): + attention_mask = uncond_inputA.attention_mask.to(device) + else: + attention_mask = None + + negative_prompt_embedsA = self.text_encoder( + uncond_inputA.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embedsB = self.text_encoder( + uncond_inputB.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embeds = ( + negative_prompt_embedsA[0] * (t_nag) + + (1 - t_nag) * negative_prompt_embedsB[0] + ) + + # negative_prompt_embeds = negative_prompt_embeds[0] + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + negative_prompt_embeds = negative_prompt_embeds.to( + dtype=prompt_embeds_dtype, device=device + ) + + negative_prompt_embeds = negative_prompt_embeds.repeat( + 1, num_images_per_prompt, 1 + ) + negative_prompt_embeds = negative_prompt_embeds.view( + batch_size * num_images_per_prompt, seq_len, -1 + ) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + # print("prompt_embeds: ",prompt_embeds) + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) + + return prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker + def run_safety_checker(self, image, device, dtype): + if self.safety_checker is None: + has_nsfw_concept = None + else: + if torch.is_tensor(image): + feature_extractor_input = self.image_processor.postprocess( + image, output_type="pil" + ) + else: + feature_extractor_input = self.image_processor.numpy_to_pil(image) + safety_checker_input = self.feature_extractor( + feature_extractor_input, return_tensors="pt" + ).to(device) + image, has_nsfw_concept = self.safety_checker( + images=image, clip_input=safety_checker_input.pixel_values.to(dtype) + ) + return image, has_nsfw_concept + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set( + inspect.signature(self.scheduler.step).parameters.keys() + ) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set( + inspect.signature(self.scheduler.step).parameters.keys() + ) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + def check_inputs( + self, + prompt, + height, + width, + strength, + callback_steps, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + ): + if strength < 0 or strength > 1: + raise ValueError( + f"The value of strength should in [0.0, 1.0] but is {strength}" + ) + + if height % 8 != 0 or width % 8 != 0: + raise ValueError( + f"`height` and `width` have to be divisible by 8 but are {height} and {width}." + ) + + if (callback_steps is None) or ( + callback_steps is not None + and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and ( + not isinstance(prompt, str) and not isinstance(prompt, list) + ): + raise ValueError( + f"`prompt` has to be of type `str` or `list` but is {type(prompt)}" + ) + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + + def prepare_latents( + self, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + image=None, + timestep=None, + is_strength_max=True, + return_noise=False, + return_image_latents=False, + ): + shape = ( + batch_size, + num_channels_latents, + height // self.vae_scale_factor, + width // self.vae_scale_factor, + ) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if (image is None or timestep is None) and not is_strength_max: + raise ValueError( + "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise." + "However, either the image or the noise timestep has not been provided." + ) + + if return_image_latents or (latents is None and not is_strength_max): + image = image.to(device=device, dtype=dtype) + image_latents = self._encode_vae_image(image=image, generator=generator) + + if latents is None: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + # if strength is 1. then initialise the latents to noise, else initial to image + noise + latents = ( + noise + if is_strength_max + else self.scheduler.add_noise(image_latents, noise, timestep) + ) + # if pure noise then scale the initial latents by the Scheduler's init sigma + latents = ( + latents * self.scheduler.init_noise_sigma + if is_strength_max + else latents + ) + else: + noise = latents.to(device) + latents = noise * self.scheduler.init_noise_sigma + + outputs = (latents,) + + if return_noise: + outputs += (noise,) + + if return_image_latents: + outputs += (image_latents,) + + return outputs + + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + if isinstance(generator, list): + image_latents = [ + self.vae.encode(image[i : i + 1]).latent_dist.sample( + generator=generator[i] + ) + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = self.vae.encode(image).latent_dist.sample( + generator=generator + ) + + image_latents = self.vae.config.scaling_factor * image_latents + + return image_latents + + def prepare_mask_latents( + self, + mask, + masked_image, + batch_size, + height, + width, + dtype, + device, + generator, + do_classifier_free_guidance, + ): + # resize the mask to latents shape as we concatenate the mask to the latents + # we do that before converting to dtype to avoid breaking in case we're using cpu_offload + # and half precision + mask = torch.nn.functional.interpolate( + mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) + ) + mask = mask.to(device=device, dtype=dtype) + + masked_image = masked_image.to(device=device, dtype=dtype) + masked_image_latents = self._encode_vae_image(masked_image, generator=generator) + + # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method + if mask.shape[0] < batch_size: + if not batch_size % mask.shape[0] == 0: + raise ValueError( + "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" + f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" + " of masks that you pass is divisible by the total requested batch size." + ) + mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) + if masked_image_latents.shape[0] < batch_size: + if not batch_size % masked_image_latents.shape[0] == 0: + raise ValueError( + "The passed images and the required batch size don't match. Images are supposed to be duplicated" + f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." + " Make sure the number of images that you pass is divisible by the total requested batch size." + ) + masked_image_latents = masked_image_latents.repeat( + batch_size // masked_image_latents.shape[0], 1, 1, 1 + ) + + mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask + masked_image_latents = ( + torch.cat([masked_image_latents] * 2) + if do_classifier_free_guidance + else masked_image_latents + ) + + # aligning device to prevent device errors when concating it with the latent model input + masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) + return mask, masked_image_latents + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, strength, device): + # get the original timestep using init_timestep + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + + t_start = max(num_inference_steps - init_timestep, 0) + timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] + + return timesteps, num_inference_steps - t_start + + @torch.no_grad() + def __call__( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.FloatTensor, PIL.Image.Image] = None, + mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + task_class: Union[torch.Tensor, float, int] = None, + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. + image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to be inpainted (which parts of the image to be masked + out with `mask_image` and repainted according to `prompt`). + mask_image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to mask `image`. White pixels in the mask are repainted + while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a single channel + (luminance) before use. If it's a tensor, it should contain one color channel (L) instead of 3, so the + expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.0): + Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a + starting point and more noise is added the higher the `strength`. The number of denoising steps depends + on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising + process runs for the full number of iterations specified in `num_inference_steps`. A value of 1 + essentially ignores `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. This parameter is modulated by `strength`. + guidance_scale (`float`, *optional*, defaults to 7.5): + A higher guidance scale value encourages the model to generate images closely linked to the text + `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide what to not include in image generation. If not defined, you need to + pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies + to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If + not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that calls every `callback_steps` steps during inference. The function is called with the + following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function is called. If not specified, the callback is called at + every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in + [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + + Examples: + + ```py + >>> import PIL + >>> import requests + >>> import torch + >>> from io import BytesIO + + >>> from diffusers import StableDiffusionInpaintPipeline + + + >>> def download_image(url): + ... response = requests.get(url) + ... return PIL.Image.open(BytesIO(response.content)).convert("RGB") + + + >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" + >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" + + >>> init_image = download_image(img_url).resize((512, 512)) + >>> mask_image = download_image(mask_url).resize((512, 512)) + + >>> pipe = StableDiffusionInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 + ... ) + >>> pipe = pipe.to("cuda") + + >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench" + >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] + ``` + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, + otherwise a `tuple` is returned where the first element is a list with the generated images and the + second element is a list of `bool`s indicating whether the corresponding generated image contains + "not-safe-for-work" (nsfw) content. + """ + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + prompt = promptA + negative_prompt = negative_promptA + # 1. Check inputs + self.check_inputs( + prompt, + height, + width, + strength, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) + if cross_attention_kwargs is not None + else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. set timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # check that number of inference steps is not < 1 - as this doesn't make sense + if num_inference_steps < 1: + raise ValueError( + f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline" + f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline." + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 5. Preprocess mask and image + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + mask_condition = mask.clone() + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 8. Check that sizes of mask, masked image and latents match + if num_channels_unet == 9: + # default case for runwayml/stable-diffusion-inpainting + num_channels_mask = mask.shape[1] + num_channels_masked_image = masked_image_latents.shape[1] + if ( + num_channels_latents + num_channels_mask + num_channels_masked_image + != self.unet.config.in_channels + ): + raise ValueError( + f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" + f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" + f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" + f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" + " `pipeline.unet` or your `mask_image` or `image` input." + ) + elif num_channels_unet != 4: + raise ValueError( + f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}." + ) + + # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 10. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = ( + torch.cat([latents] * 2) if do_classifier_free_guidance else latents + ) + + # concat latents, mask, masked_image_latents in the channel dimension + latent_model_input = self.scheduler.scale_model_input( + latent_model_input, t + ) + + if num_channels_unet == 9: + latent_model_input = torch.cat( + [latent_model_input, mask, masked_image_latents], dim=1 + ) + + # predict the noise residual + if task_class is not None: + noise_pred = self.unet( + sample=latent_model_input, + timestep=t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + task_class=task_class, + )[0] + else: + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * ( + noise_pred_text - noise_pred_uncond + ) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step( + noise_pred, t, latents, **extra_step_kwargs, return_dict=False + )[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = ( + 1 - init_mask + ) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ( + (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0 + ): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(self, i, t, {}) + + if not output_type == "latent": + condition_kwargs = {} + if isinstance(self.vae, AsymmetricAutoencoderKL): + init_image = init_image.to( + device=device, dtype=masked_image_latents.dtype + ) + init_image_condition = init_image.clone() + init_image = self._encode_vae_image(init_image, generator=generator) + mask_condition = mask_condition.to( + device=device, dtype=masked_image_latents.dtype + ) + condition_kwargs = { + "image": init_image_condition, + "mask": mask_condition, + } + image = self.vae.decode( + latents / self.vae.config.scaling_factor, + return_dict=False, + **condition_kwargs, + )[0] + image, has_nsfw_concept = self.run_safety_checker( + image, device, prompt_embeds.dtype + ) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess( + image, output_type=output_type, do_denormalize=do_denormalize + ) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput( + images=image, nsfw_content_detected=has_nsfw_concept + ) diff --git a/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py b/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py new file mode 100644 index 0000000..cba0f8f --- /dev/null +++ b/py/iopaint/model/power_paint/pipeline_powerpaint_controlnet.py @@ -0,0 +1,1775 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# 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. + +# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/ + +import inspect +import warnings +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import numpy as np +import PIL.Image +import torch +import torch.nn.functional as F +from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer + +from diffusers.image_processor import VaeImageProcessor +from diffusers.loaders import FromSingleFileMixin, LoraLoaderMixin, TextualInversionLoaderMixin +from diffusers.models import AutoencoderKL, ControlNetModel, UNet2DConditionModel +from diffusers.schedulers import KarrasDiffusionSchedulers +from diffusers.utils import ( + is_accelerate_available, + is_accelerate_version, + logging, + replace_example_docstring, +) +from diffusers.utils.torch_utils import randn_tensor,is_compiled_module +from diffusers.pipelines.pipeline_utils import DiffusionPipeline +from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput +from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker +from diffusers.pipelines.controlnet import MultiControlNetModel + + + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +EXAMPLE_DOC_STRING = """ + Examples: + ```py + >>> # !pip install transformers accelerate + >>> from diffusers import StableDiffusionControlNetInpaintPipeline, ControlNetModel, DDIMScheduler + >>> from diffusers.utils import load_image + >>> import numpy as np + >>> import torch + + >>> init_image = load_image( + ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png" + ... ) + >>> init_image = init_image.resize((512, 512)) + + >>> generator = torch.Generator(device="cpu").manual_seed(1) + + >>> mask_image = load_image( + ... "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png" + ... ) + >>> mask_image = mask_image.resize((512, 512)) + + + >>> def make_inpaint_condition(image, image_mask): + ... image = np.array(image.convert("RGB")).astype(np.float32) / 255.0 + ... image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0 + + ... assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size" + ... image[image_mask > 0.5] = -1.0 # set as masked pixel + ... image = np.expand_dims(image, 0).transpose(0, 3, 1, 2) + ... image = torch.from_numpy(image) + ... return image + + + >>> control_image = make_inpaint_condition(init_image, mask_image) + + >>> controlnet = ControlNetModel.from_pretrained( + ... "lllyasviel/control_v11p_sd15_inpaint", torch_dtype=torch.float16 + ... ) + >>> pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-v1-5", controlnet=controlnet, torch_dtype=torch.float16 + ... ) + + >>> pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) + >>> pipe.enable_model_cpu_offload() + + >>> # generate image + >>> image = pipe( + ... "a handsome man with ray-ban sunglasses", + ... num_inference_steps=20, + ... generator=generator, + ... eta=1.0, + ... image=init_image, + ... mask_image=mask_image, + ... control_image=control_image, + ... ).images[0] + ``` +""" + + +# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.prepare_mask_and_masked_image +def prepare_mask_and_masked_image(image, mask, height, width, return_image=False): + """ + Prepares a pair (image, mask) to be consumed by the Stable Diffusion pipeline. This means that those inputs will be + converted to ``torch.Tensor`` with shapes ``batch x channels x height x width`` where ``channels`` is ``3`` for the + ``image`` and ``1`` for the ``mask``. + + The ``image`` will be converted to ``torch.float32`` and normalized to be in ``[-1, 1]``. The ``mask`` will be + binarized (``mask > 0.5``) and cast to ``torch.float32`` too. + + Args: + image (Union[np.array, PIL.Image, torch.Tensor]): The image to inpaint. + It can be a ``PIL.Image``, or a ``height x width x 3`` ``np.array`` or a ``channels x height x width`` + ``torch.Tensor`` or a ``batch x channels x height x width`` ``torch.Tensor``. + mask (_type_): The mask to apply to the image, i.e. regions to inpaint. + It can be a ``PIL.Image``, or a ``height x width`` ``np.array`` or a ``1 x height x width`` + ``torch.Tensor`` or a ``batch x 1 x height x width`` ``torch.Tensor``. + + + Raises: + ValueError: ``torch.Tensor`` images should be in the ``[-1, 1]`` range. ValueError: ``torch.Tensor`` mask + should be in the ``[0, 1]`` range. ValueError: ``mask`` and ``image`` should have the same spatial dimensions. + TypeError: ``mask`` is a ``torch.Tensor`` but ``image`` is not + (ot the other way around). + + Returns: + tuple[torch.Tensor]: The pair (mask, masked_image) as ``torch.Tensor`` with 4 + dimensions: ``batch x channels x height x width``. + """ + + if image is None: + raise ValueError("`image` input cannot be undefined.") + + if mask is None: + raise ValueError("`mask_image` input cannot be undefined.") + + if isinstance(image, torch.Tensor): + if not isinstance(mask, torch.Tensor): + raise TypeError(f"`image` is a torch.Tensor but `mask` (type: {type(mask)} is not") + + # Batch single image + if image.ndim == 3: + assert image.shape[0] == 3, "Image outside a batch should be of shape (3, H, W)" + image = image.unsqueeze(0) + + # Batch and add channel dim for single mask + if mask.ndim == 2: + mask = mask.unsqueeze(0).unsqueeze(0) + + # Batch single mask or add channel dim + if mask.ndim == 3: + # Single batched mask, no channel dim or single mask not batched but channel dim + if mask.shape[0] == 1: + mask = mask.unsqueeze(0) + + # Batched masks no channel dim + else: + mask = mask.unsqueeze(1) + + assert image.ndim == 4 and mask.ndim == 4, "Image and Mask must have 4 dimensions" + assert image.shape[-2:] == mask.shape[-2:], "Image and Mask must have the same spatial dimensions" + assert image.shape[0] == mask.shape[0], "Image and Mask must have the same batch size" + + # Check image is in [-1, 1] + if image.min() < -1 or image.max() > 1: + raise ValueError("Image should be in [-1, 1] range") + + # Check mask is in [0, 1] + if mask.min() < 0 or mask.max() > 1: + raise ValueError("Mask should be in [0, 1] range") + + # Binarize mask + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + + # Image as float32 + image = image.to(dtype=torch.float32) + elif isinstance(mask, torch.Tensor): + raise TypeError(f"`mask` is a torch.Tensor but `image` (type: {type(image)} is not") + else: + # preprocess image + if isinstance(image, (PIL.Image.Image, np.ndarray)): + image = [image] + if isinstance(image, list) and isinstance(image[0], PIL.Image.Image): + # resize all images w.r.t passed height an width + image = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in image] + image = [np.array(i.convert("RGB"))[None, :] for i in image] + image = np.concatenate(image, axis=0) + elif isinstance(image, list) and isinstance(image[0], np.ndarray): + image = np.concatenate([i[None, :] for i in image], axis=0) + + image = image.transpose(0, 3, 1, 2) + image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0 + + # preprocess mask + if isinstance(mask, (PIL.Image.Image, np.ndarray)): + mask = [mask] + + if isinstance(mask, list) and isinstance(mask[0], PIL.Image.Image): + mask = [i.resize((width, height), resample=PIL.Image.LANCZOS) for i in mask] + mask = np.concatenate([np.array(m.convert("L"))[None, None, :] for m in mask], axis=0) + mask = mask.astype(np.float32) / 255.0 + elif isinstance(mask, list) and isinstance(mask[0], np.ndarray): + mask = np.concatenate([m[None, None, :] for m in mask], axis=0) + + mask[mask < 0.5] = 0 + mask[mask >= 0.5] = 1 + mask = torch.from_numpy(mask) + + masked_image = image * (mask < 0.5) + + # n.b. ensure backwards compatibility as old function does not return image + if return_image: + return mask, masked_image, image + + return mask, masked_image + + +class StableDiffusionControlNetInpaintPipeline( + DiffusionPipeline, TextualInversionLoaderMixin, LoraLoaderMixin, FromSingleFileMixin +): + r""" + Pipeline for text-to-image generation using Stable Diffusion with ControlNet guidance. + + This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the + library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.) + + In addition the pipeline inherits the following loading methods: + - *Textual-Inversion*: [`loaders.TextualInversionLoaderMixin.load_textual_inversion`] + + + + This pipeline can be used both with checkpoints that have been specifically fine-tuned for inpainting, such as + [runwayml/stable-diffusion-inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) + as well as default text-to-image stable diffusion checkpoints, such as + [runwayml/stable-diffusion-v1-5](https://huggingface.co/runwayml/stable-diffusion-v1-5). + Default text-to-image stable diffusion checkpoints might be preferable for controlnets that have been fine-tuned on + those, such as [lllyasviel/control_v11p_sd15_inpaint](https://huggingface.co/lllyasviel/control_v11p_sd15_inpaint). + + + + Args: + vae ([`AutoencoderKL`]): + Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations. + text_encoder ([`CLIPTextModel`]): + Frozen text-encoder. Stable Diffusion uses the text portion of + [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically + the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant. + tokenizer (`CLIPTokenizer`): + Tokenizer of class + [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer). + unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents. + controlnet ([`ControlNetModel`] or `List[ControlNetModel]`): + Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets + as a list, the outputs from each ControlNet are added together to create one combined additional + conditioning. + scheduler ([`SchedulerMixin`]): + A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of + [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`]. + safety_checker ([`StableDiffusionSafetyChecker`]): + Classification module that estimates whether generated images could be considered offensive or harmful. + Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details. + feature_extractor ([`CLIPImageProcessor`]): + Model that extracts features from generated images to be used as inputs for the `safety_checker`. + """ + _optional_components = ["safety_checker", "feature_extractor"] + + def __init__( + self, + vae: AutoencoderKL, + text_encoder: CLIPTextModel, + tokenizer: CLIPTokenizer, + unet: UNet2DConditionModel, + controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel], + scheduler: KarrasDiffusionSchedulers, + safety_checker: StableDiffusionSafetyChecker, + feature_extractor: CLIPImageProcessor, + requires_safety_checker: bool = True, + ): + super().__init__() + + if safety_checker is None and requires_safety_checker: + logger.warning( + f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure" + " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" + " results in services or applications open to the public. Both the diffusers team and Hugging Face" + " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" + " it only for use-cases that involve analyzing network behavior or auditing its results. For more" + " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." + ) + + if safety_checker is not None and feature_extractor is None: + raise ValueError( + "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety" + " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead." + ) + + if isinstance(controlnet, (list, tuple)): + controlnet = MultiControlNetModel(controlnet) + + self.register_modules( + vae=vae, + text_encoder=text_encoder, + tokenizer=tokenizer, + unet=unet, + controlnet=controlnet, + scheduler=scheduler, + safety_checker=safety_checker, + feature_extractor=feature_extractor, + ) + self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) + self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor) + self.control_image_processor = VaeImageProcessor( + vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False + ) + self.register_to_config(requires_safety_checker=requires_safety_checker) + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_slicing + def enable_vae_slicing(self): + r""" + Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to + compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. + """ + self.vae.enable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_slicing + def disable_vae_slicing(self): + r""" + Disable sliced VAE decoding. If `enable_vae_slicing` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_slicing() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_vae_tiling + def enable_vae_tiling(self): + r""" + Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to + compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow + processing larger images. + """ + self.vae.enable_tiling() + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.disable_vae_tiling + def disable_vae_tiling(self): + r""" + Disable tiled VAE decoding. If `enable_vae_tiling` was previously enabled, this method will go back to + computing decoding in one step. + """ + self.vae.disable_tiling() + + def enable_model_cpu_offload(self, gpu_id=0): + r""" + Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared + to `enable_sequential_cpu_offload`, this method moves one whole model at a time to the GPU when its `forward` + method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with + `enable_sequential_cpu_offload`, but performance is much better due to the iterative execution of the `unet`. + """ + if is_accelerate_available() and is_accelerate_version(">=", "0.17.0.dev0"): + from accelerate import cpu_offload_with_hook + else: + raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.") + + device = torch.device(f"cuda:{gpu_id}") + + hook = None + for cpu_offloaded_model in [self.text_encoder, self.unet, self.vae]: + _, hook = cpu_offload_with_hook(cpu_offloaded_model, device, prev_module_hook=hook) + + if self.safety_checker is not None: + # the safety checker can offload the vae again + _, hook = cpu_offload_with_hook(self.safety_checker, device, prev_module_hook=hook) + + # control net hook has be manually offloaded as it alternates with unet + cpu_offload_with_hook(self.controlnet, device) + + # We'll offload the last model manually. + self.final_offload_hook = hook + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt + def _encode_prompt( + self, + promptA, + promptB, + t, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA=None, + negative_promptB=None, + t_nag = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + lora_scale: Optional[float] = None, + ): + r""" + Encodes the prompt into text encoder hidden states. + + Args: + prompt (`str` or `List[str]`, *optional*): + prompt to be encoded + device: (`torch.device`): + torch device + num_images_per_prompt (`int`): + number of images that should be generated per prompt + do_classifier_free_guidance (`bool`): + whether to use classifier free guidance or not + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + lora_scale (`float`, *optional*): + A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. + """ + # set lora scale so that monkey patched LoRA + # function of text encoder can correctly access it + if lora_scale is not None and isinstance(self, LoraLoaderMixin): + self._lora_scale = lora_scale + + prompt = promptA + negative_prompt = negative_promptA + + if promptA is not None and isinstance(promptA, str): + batch_size = 1 + elif promptA is not None and isinstance(promptA, list): + batch_size = len(promptA) + else: + batch_size = prompt_embeds.shape[0] + + if prompt_embeds is None: + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + promptA = self.maybe_convert_prompt(promptA, self.tokenizer) + + text_inputsA = self.tokenizer( + promptA, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_inputsB = self.tokenizer( + promptB, + padding="max_length", + max_length=self.tokenizer.model_max_length, + truncation=True, + return_tensors="pt", + ) + text_input_idsA = text_inputsA.input_ids + text_input_idsB = text_inputsB.input_ids + untruncated_ids = self.tokenizer(promptA, padding="longest", return_tensors="pt").input_ids + + if untruncated_ids.shape[-1] >= text_input_idsA.shape[-1] and not torch.equal( + text_input_idsA, untruncated_ids + ): + removed_text = self.tokenizer.batch_decode( + untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] + ) + logger.warning( + "The following part of your input was truncated because CLIP can only handle sequences up to" + f" {self.tokenizer.model_max_length} tokens: {removed_text}" + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = text_inputsA.attention_mask.to(device) + else: + attention_mask = None + + # print("text_input_idsA: ",text_input_idsA) + # print("text_input_idsB: ",text_input_idsB) + # print('t: ',t) + + prompt_embedsA = self.text_encoder( + text_input_idsA.to(device), + attention_mask=attention_mask, + ) + prompt_embedsA = prompt_embedsA[0] + + prompt_embedsB = self.text_encoder( + text_input_idsB.to(device), + attention_mask=attention_mask, + ) + prompt_embedsB = prompt_embedsB[0] + prompt_embeds = prompt_embedsA*(t)+(1-t)*prompt_embedsB + # print("prompt_embeds: ",prompt_embeds) + + if self.text_encoder is not None: + prompt_embeds_dtype = self.text_encoder.dtype + elif self.unet is not None: + prompt_embeds_dtype = self.unet.dtype + else: + prompt_embeds_dtype = prompt_embeds.dtype + + prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + bs_embed, seq_len, _ = prompt_embeds.shape + # duplicate text embeddings for each generation per prompt, using mps friendly method + prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) + prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) + + # get unconditional embeddings for classifier free guidance + if do_classifier_free_guidance and negative_prompt_embeds is None: + uncond_tokensA: List[str] + uncond_tokensB: List[str] + if negative_prompt is None: + uncond_tokensA = [""] * batch_size + uncond_tokensB = [""] * batch_size + elif prompt is not None and type(prompt) is not type(negative_prompt): + raise TypeError( + f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" + f" {type(prompt)}." + ) + elif isinstance(negative_prompt, str): + uncond_tokensA = [negative_promptA] + uncond_tokensB = [negative_promptB] + elif batch_size != len(negative_prompt): + raise ValueError( + f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" + f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" + " the batch size of `prompt`." + ) + else: + uncond_tokensA = negative_promptA + uncond_tokensB = negative_promptB + + # textual inversion: procecss multi-vector tokens if necessary + if isinstance(self, TextualInversionLoaderMixin): + uncond_tokensA = self.maybe_convert_prompt(uncond_tokensA, self.tokenizer) + uncond_tokensB = self.maybe_convert_prompt(uncond_tokensB, self.tokenizer) + + max_length = prompt_embeds.shape[1] + uncond_inputA = self.tokenizer( + uncond_tokensA, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + uncond_inputB = self.tokenizer( + uncond_tokensB, + padding="max_length", + max_length=max_length, + truncation=True, + return_tensors="pt", + ) + + if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: + attention_mask = uncond_inputA.attention_mask.to(device) + else: + attention_mask = None + + negative_prompt_embedsA = self.text_encoder( + uncond_inputA.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embedsB = self.text_encoder( + uncond_inputB.input_ids.to(device), + attention_mask=attention_mask, + ) + negative_prompt_embeds = negative_prompt_embedsA[0]*(t_nag)+(1-t_nag)*negative_prompt_embedsB[0] + + # negative_prompt_embeds = negative_prompt_embeds[0] + + if do_classifier_free_guidance: + # duplicate unconditional embeddings for each generation per prompt, using mps friendly method + seq_len = negative_prompt_embeds.shape[1] + + negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) + + negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) + negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) + + # For classifier free guidance, we need to do two forward passes. + # Here we concatenate the unconditional and text embeddings into a single batch + # to avoid doing two forward passes + # print("prompt_embeds: ",prompt_embeds) + prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) + + return prompt_embeds + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker + def run_safety_checker(self, image, device, dtype): + if self.safety_checker is None: + has_nsfw_concept = None + else: + if torch.is_tensor(image): + feature_extractor_input = self.image_processor.postprocess(image, output_type="pil") + else: + feature_extractor_input = self.image_processor.numpy_to_pil(image) + safety_checker_input = self.feature_extractor(feature_extractor_input, return_tensors="pt").to(device) + image, has_nsfw_concept = self.safety_checker( + images=image, clip_input=safety_checker_input.pixel_values.to(dtype) + ) + return image, has_nsfw_concept + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents + def decode_latents(self, latents): + warnings.warn( + "The decode_latents method is deprecated and will be removed in a future version. Please" + " use VaeImageProcessor instead", + FutureWarning, + ) + latents = 1 / self.vae.config.scaling_factor * latents + image = self.vae.decode(latents, return_dict=False)[0] + image = (image / 2 + 0.5).clamp(0, 1) + # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 + image = image.cpu().permute(0, 2, 3, 1).float().numpy() + return image + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs + def prepare_extra_step_kwargs(self, generator, eta): + # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature + # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. + # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 + # and should be between [0, 1] + + accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys()) + extra_step_kwargs = {} + if accepts_eta: + extra_step_kwargs["eta"] = eta + + # check if the scheduler accepts generator + accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys()) + if accepts_generator: + extra_step_kwargs["generator"] = generator + return extra_step_kwargs + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps + def get_timesteps(self, num_inference_steps, strength, device): + # get the original timestep using init_timestep + init_timestep = min(int(num_inference_steps * strength), num_inference_steps) + + t_start = max(num_inference_steps - init_timestep, 0) + timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :] + + return timesteps, num_inference_steps - t_start + + def check_inputs( + self, + prompt, + image, + height, + width, + callback_steps, + negative_prompt=None, + prompt_embeds=None, + negative_prompt_embeds=None, + controlnet_conditioning_scale=1.0, + control_guidance_start=0.0, + control_guidance_end=1.0, + ): + if height % 8 != 0 or width % 8 != 0: + raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.") + + if (callback_steps is None) or ( + callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0) + ): + raise ValueError( + f"`callback_steps` has to be a positive integer but is {callback_steps} of type" + f" {type(callback_steps)}." + ) + + if prompt is not None and prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to" + " only forward one of the two." + ) + elif prompt is None and prompt_embeds is None: + raise ValueError( + "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined." + ) + elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)): + raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}") + + if negative_prompt is not None and negative_prompt_embeds is not None: + raise ValueError( + f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:" + f" {negative_prompt_embeds}. Please make sure to only forward one of the two." + ) + + if prompt_embeds is not None and negative_prompt_embeds is not None: + if prompt_embeds.shape != negative_prompt_embeds.shape: + raise ValueError( + "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but" + f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`" + f" {negative_prompt_embeds.shape}." + ) + + # `prompt` needs more sophisticated handling when there are multiple + # conditionings. + if isinstance(self.controlnet, MultiControlNetModel): + if isinstance(prompt, list): + logger.warning( + f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}" + " prompts. The conditionings will be fixed across the prompts." + ) + + # Check `image` + is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance( + self.controlnet, torch._dynamo.eval_frame.OptimizedModule + ) + + if ( + isinstance(self.controlnet, ControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, ControlNetModel) + ): + self.check_image(image, prompt, prompt_embeds) + elif ( + isinstance(self.controlnet, MultiControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, MultiControlNetModel) + ): + if not isinstance(image, list): + raise TypeError("For multiple controlnets: `image` must be type `list`") + + # When `image` is a nested list: + # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]]) + elif any(isinstance(i, list) for i in image): + raise ValueError("A single batch of multiple conditionings are supported at the moment.") + elif len(image) != len(self.controlnet.nets): + raise ValueError( + f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets." + ) + + for image_ in image: + self.check_image(image_, prompt, prompt_embeds) + else: + assert False + + # Check `controlnet_conditioning_scale` + if ( + isinstance(self.controlnet, ControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, ControlNetModel) + ): + if not isinstance(controlnet_conditioning_scale, float): + raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.") + elif ( + isinstance(self.controlnet, MultiControlNetModel) + or is_compiled + and isinstance(self.controlnet._orig_mod, MultiControlNetModel) + ): + if isinstance(controlnet_conditioning_scale, list): + if any(isinstance(i, list) for i in controlnet_conditioning_scale): + raise ValueError("A single batch of multiple conditionings are supported at the moment.") + elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len( + self.controlnet.nets + ): + raise ValueError( + "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have" + " the same length as the number of controlnets" + ) + else: + assert False + + if len(control_guidance_start) != len(control_guidance_end): + raise ValueError( + f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list." + ) + + if isinstance(self.controlnet, MultiControlNetModel): + if len(control_guidance_start) != len(self.controlnet.nets): + raise ValueError( + f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}." + ) + + for start, end in zip(control_guidance_start, control_guidance_end): + if start >= end: + raise ValueError( + f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}." + ) + if start < 0.0: + raise ValueError(f"control guidance start: {start} can't be smaller than 0.") + if end > 1.0: + raise ValueError(f"control guidance end: {end} can't be larger than 1.0.") + + # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.check_image + def check_image(self, image, prompt, prompt_embeds): + image_is_pil = isinstance(image, PIL.Image.Image) + image_is_tensor = isinstance(image, torch.Tensor) + image_is_np = isinstance(image, np.ndarray) + image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image) + image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor) + image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray) + + if ( + not image_is_pil + and not image_is_tensor + and not image_is_np + and not image_is_pil_list + and not image_is_tensor_list + and not image_is_np_list + ): + raise TypeError( + f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}" + ) + + if image_is_pil: + image_batch_size = 1 + else: + image_batch_size = len(image) + + if prompt is not None and isinstance(prompt, str): + prompt_batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + prompt_batch_size = len(prompt) + elif prompt_embeds is not None: + prompt_batch_size = prompt_embeds.shape[0] + + if image_batch_size != 1 and image_batch_size != prompt_batch_size: + raise ValueError( + f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}" + ) + + # Copied from diffusers.pipelines.controlnet.pipeline_controlnet.StableDiffusionControlNetPipeline.prepare_image + def prepare_control_image( + self, + image, + width, + height, + batch_size, + num_images_per_prompt, + device, + dtype, + do_classifier_free_guidance=False, + guess_mode=False, + ): + image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32) + image_batch_size = image.shape[0] + + if image_batch_size == 1: + repeat_by = batch_size + else: + # image batch size is the same as prompt batch size + repeat_by = num_images_per_prompt + + image = image.repeat_interleave(repeat_by, dim=0) + + image = image.to(device=device, dtype=dtype) + + if do_classifier_free_guidance and not guess_mode: + image = torch.cat([image] * 2) + + return image + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline.prepare_latents + def prepare_latents( + self, + batch_size, + num_channels_latents, + height, + width, + dtype, + device, + generator, + latents=None, + image=None, + timestep=None, + is_strength_max=True, + return_noise=False, + return_image_latents=False, + ): + shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) + if isinstance(generator, list) and len(generator) != batch_size: + raise ValueError( + f"You have passed a list of generators of length {len(generator)}, but requested an effective batch" + f" size of {batch_size}. Make sure the batch size matches the length of the generators." + ) + + if (image is None or timestep is None) and not is_strength_max: + raise ValueError( + "Since strength < 1. initial latents are to be initialised as a combination of Image + Noise." + "However, either the image or the noise timestep has not been provided." + ) + + if return_image_latents or (latents is None and not is_strength_max): + image = image.to(device=device, dtype=dtype) + image_latents = self._encode_vae_image(image=image, generator=generator) + + if latents is None: + noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype) + # if strength is 1. then initialise the latents to noise, else initial to image + noise + latents = noise if is_strength_max else self.scheduler.add_noise(image_latents, noise, timestep) + # if pure noise then scale the initial latents by the Scheduler's init sigma + latents = latents * self.scheduler.init_noise_sigma if is_strength_max else latents + else: + noise = latents.to(device) + latents = noise * self.scheduler.init_noise_sigma + + outputs = (latents,) + + if return_noise: + outputs += (noise,) + + if return_image_latents: + outputs += (image_latents,) + + return outputs + + def _default_height_width(self, height, width, image): + # NOTE: It is possible that a list of images have different + # dimensions for each image, so just checking the first image + # is not _exactly_ correct, but it is simple. + while isinstance(image, list): + image = image[0] + + if height is None: + if isinstance(image, PIL.Image.Image): + height = image.height + elif isinstance(image, torch.Tensor): + height = image.shape[2] + + height = (height // 8) * 8 # round down to nearest multiple of 8 + + if width is None: + if isinstance(image, PIL.Image.Image): + width = image.width + elif isinstance(image, torch.Tensor): + width = image.shape[3] + + width = (width // 8) * 8 # round down to nearest multiple of 8 + + return height, width + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline.prepare_mask_latents + def prepare_mask_latents( + self, mask, masked_image, batch_size, height, width, dtype, device, generator, do_classifier_free_guidance + ): + # resize the mask to latents shape as we concatenate the mask to the latents + # we do that before converting to dtype to avoid breaking in case we're using cpu_offload + # and half precision + mask = torch.nn.functional.interpolate( + mask, size=(height // self.vae_scale_factor, width // self.vae_scale_factor) + ) + mask = mask.to(device=device, dtype=dtype) + + masked_image = masked_image.to(device=device, dtype=dtype) + masked_image_latents = self._encode_vae_image(masked_image, generator=generator) + + # duplicate mask and masked_image_latents for each generation per prompt, using mps friendly method + if mask.shape[0] < batch_size: + if not batch_size % mask.shape[0] == 0: + raise ValueError( + "The passed mask and the required batch size don't match. Masks are supposed to be duplicated to" + f" a total batch size of {batch_size}, but {mask.shape[0]} masks were passed. Make sure the number" + " of masks that you pass is divisible by the total requested batch size." + ) + mask = mask.repeat(batch_size // mask.shape[0], 1, 1, 1) + if masked_image_latents.shape[0] < batch_size: + if not batch_size % masked_image_latents.shape[0] == 0: + raise ValueError( + "The passed images and the required batch size don't match. Images are supposed to be duplicated" + f" to a total batch size of {batch_size}, but {masked_image_latents.shape[0]} images were passed." + " Make sure the number of images that you pass is divisible by the total requested batch size." + ) + masked_image_latents = masked_image_latents.repeat(batch_size // masked_image_latents.shape[0], 1, 1, 1) + + mask = torch.cat([mask] * 2) if do_classifier_free_guidance else mask + masked_image_latents = ( + torch.cat([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents + ) + + # aligning device to prevent device errors when concating it with the latent model input + masked_image_latents = masked_image_latents.to(device=device, dtype=dtype) + return mask, masked_image_latents + + # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_inpaint.StableDiffusionInpaintPipeline._encode_vae_image + def _encode_vae_image(self, image: torch.Tensor, generator: torch.Generator): + if isinstance(generator, list): + image_latents = [ + self.vae.encode(image[i : i + 1]).latent_dist.sample(generator=generator[i]) + for i in range(image.shape[0]) + ] + image_latents = torch.cat(image_latents, dim=0) + else: + image_latents = self.vae.encode(image).latent_dist.sample(generator=generator) + + image_latents = self.vae.config.scaling_factor * image_latents + + return image_latents + + @torch.no_grad() + def predict_woControl( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.FloatTensor, PIL.Image.Image] = None, + mask_image: Union[torch.FloatTensor, PIL.Image.Image] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + task_class: Union[torch.Tensor, float, int] = None, + ): + r""" + The call function to the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. + image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to be inpainted (which parts of the image to be masked + out with `mask_image` and repainted according to `prompt`). + mask_image (`PIL.Image.Image`): + `Image` or tensor representing an image batch to mask `image`. White pixels in the mask are repainted + while black pixels are preserved. If `mask_image` is a PIL image, it is converted to a single channel + (luminance) before use. If it's a tensor, it should contain one color channel (L) instead of 3, so the + expected shape would be `(B, H, W, 1)`. + height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.0): + Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a + starting point and more noise is added the higher the `strength`. The number of denoising steps depends + on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising + process runs for the full number of iterations specified in `num_inference_steps`. A value of 1 + essentially ignores `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. This parameter is modulated by `strength`. + guidance_scale (`float`, *optional*, defaults to 7.5): + A higher guidance scale value encourages the model to generate images closely linked to the text + `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide what to not include in image generation. If not defined, you need to + pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies + to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make + generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor is generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not + provided, text embeddings are generated from the `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If + not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generated image. Choose between `PIL.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that calls every `callback_steps` steps during inference. The function is called with the + following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function is called. If not specified, the callback is called at + every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in + [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + + Examples: + + ```py + >>> import PIL + >>> import requests + >>> import torch + >>> from io import BytesIO + + >>> from diffusers import StableDiffusionInpaintPipeline + + + >>> def download_image(url): + ... response = requests.get(url) + ... return PIL.Image.open(BytesIO(response.content)).convert("RGB") + + + >>> img_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo.png" + >>> mask_url = "https://raw.githubusercontent.com/CompVis/latent-diffusion/main/data/inpainting_examples/overture-creations-5sI6fQgYIuo_mask.png" + + >>> init_image = download_image(img_url).resize((512, 512)) + >>> mask_image = download_image(mask_url).resize((512, 512)) + + >>> pipe = StableDiffusionInpaintPipeline.from_pretrained( + ... "runwayml/stable-diffusion-inpainting", torch_dtype=torch.float16 + ... ) + >>> pipe = pipe.to("cuda") + + >>> prompt = "Face of a yellow cat, high resolution, sitting on a park bench" + >>> image = pipe(prompt=prompt, image=init_image, mask_image=mask_image).images[0] + ``` + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, + otherwise a `tuple` is returned where the first element is a list with the generated images and the + second element is a list of `bool`s indicating whether the corresponding generated image contains + "not-safe-for-work" (nsfw) content. + """ + # 0. Default height and width to unet + height = height or self.unet.config.sample_size * self.vae_scale_factor + width = width or self.unet.config.sample_size * self.vae_scale_factor + prompt = promptA + negative_prompt = negative_promptA + # 1. Check inputs + self.check_inputs( + prompt, + height, + width, + strength, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. set timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # check that number of inference steps is not < 1 - as this doesn't make sense + if num_inference_steps < 1: + raise ValueError( + f"After adjusting the num_inference_steps by strength parameter: {strength}, the number of pipeline" + f"steps is {num_inference_steps} which is < 1 and not appropriate for this pipeline." + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 5. Preprocess mask and image + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + mask_condition = mask.clone() + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 8. Check that sizes of mask, masked image and latents match + if num_channels_unet == 9: + # default case for runwayml/stable-diffusion-inpainting + num_channels_mask = mask.shape[1] + num_channels_masked_image = masked_image_latents.shape[1] + if num_channels_latents + num_channels_mask + num_channels_masked_image != self.unet.config.in_channels: + raise ValueError( + f"Incorrect configuration settings! The config of `pipeline.unet`: {self.unet.config} expects" + f" {self.unet.config.in_channels} but received `num_channels_latents`: {num_channels_latents} +" + f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}" + f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of" + " `pipeline.unet` or your `mask_image` or `image` input." + ) + elif num_channels_unet != 4: + raise ValueError( + f"The unet {self.unet.__class__} should have either 4 or 9 input channels, not {self.unet.config.in_channels}." + ) + + # 9. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 10. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + + # concat latents, mask, masked_image_latents in the channel dimension + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + if num_channels_unet == 9: + latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1) + + # predict the noise residual + if task_class is not None: + noise_pred = self.unet( + sample = latent_model_input, + timestep = t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + task_class = task_class, + )[0] + else: + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = (1 - init_mask) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + if not output_type == "latent": + condition_kwargs = {} + if isinstance(self.vae, AsymmetricAutoencoderKL): + init_image = init_image.to(device=device, dtype=masked_image_latents.dtype) + init_image_condition = init_image.clone() + init_image = self._encode_vae_image(init_image, generator=generator) + mask_condition = mask_condition.to(device=device, dtype=masked_image_latents.dtype) + condition_kwargs = {"image": init_image_condition, "mask": mask_condition} + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, **condition_kwargs)[0] + image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) + + + @torch.no_grad() + @replace_example_docstring(EXAMPLE_DOC_STRING) + def __call__( + self, + promptA: Union[str, List[str]] = None, + promptB: Union[str, List[str]] = None, + image: Union[torch.Tensor, PIL.Image.Image] = None, + mask_image: Union[torch.Tensor, PIL.Image.Image] = None, + control_image: Union[ + torch.FloatTensor, + PIL.Image.Image, + np.ndarray, + List[torch.FloatTensor], + List[PIL.Image.Image], + List[np.ndarray], + ] = None, + height: Optional[int] = None, + width: Optional[int] = None, + strength: float = 1.0, + tradoff: float = 1.0, + tradoff_nag: float = 1.0, + num_inference_steps: int = 50, + guidance_scale: float = 7.5, + negative_promptA: Optional[Union[str, List[str]]] = None, + negative_promptB: Optional[Union[str, List[str]]] = None, + num_images_per_prompt: Optional[int] = 1, + eta: float = 0.0, + generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, + latents: Optional[torch.FloatTensor] = None, + prompt_embeds: Optional[torch.FloatTensor] = None, + negative_prompt_embeds: Optional[torch.FloatTensor] = None, + output_type: Optional[str] = "pil", + return_dict: bool = True, + callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, + callback_steps: int = 1, + cross_attention_kwargs: Optional[Dict[str, Any]] = None, + controlnet_conditioning_scale: Union[float, List[float]] = 0.5, + guess_mode: bool = False, + control_guidance_start: Union[float, List[float]] = 0.0, + control_guidance_end: Union[float, List[float]] = 1.0, + ): + r""" + Function invoked when calling the pipeline for generation. + + Args: + prompt (`str` or `List[str]`, *optional*): + The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. + instead. + image (`torch.FloatTensor`, `PIL.Image.Image`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, + `List[List[torch.FloatTensor]]`, or `List[List[PIL.Image.Image]]`): + The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If + the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can + also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If + height and/or width are passed, `image` is resized according to them. If multiple ControlNets are + specified in init, images must be passed as a list such that each element of the list can be correctly + batched for input to a single controlnet. + height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The height in pixels of the generated image. + width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): + The width in pixels of the generated image. + strength (`float`, *optional*, defaults to 1.): + Conceptually, indicates how much to transform the masked portion of the reference `image`. Must be + between 0 and 1. `image` will be used as a starting point, adding more noise to it the larger the + `strength`. The number of denoising steps depends on the amount of noise initially added. When + `strength` is 1, added noise will be maximum and the denoising process will run for the full number of + iterations specified in `num_inference_steps`. A value of 1, therefore, essentially ignores the masked + portion of the reference `image`. + num_inference_steps (`int`, *optional*, defaults to 50): + The number of denoising steps. More denoising steps usually lead to a higher quality image at the + expense of slower inference. + guidance_scale (`float`, *optional*, defaults to 7.5): + Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). + `guidance_scale` is defined as `w` of equation 2. of [Imagen + Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > + 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, + usually at the expense of lower image quality. + negative_prompt (`str` or `List[str]`, *optional*): + The prompt or prompts not to guide the image generation. If not defined, one has to pass + `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is + less than `1`). + num_images_per_prompt (`int`, *optional*, defaults to 1): + The number of images to generate per prompt. + eta (`float`, *optional*, defaults to 0.0): + Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to + [`schedulers.DDIMScheduler`], will be ignored for others. + generator (`torch.Generator` or `List[torch.Generator]`, *optional*): + One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) + to make generation deterministic. + latents (`torch.FloatTensor`, *optional*): + Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image + generation. Can be used to tweak the same generation with different prompts. If not provided, a latents + tensor will ge generated by sampling using the supplied random `generator`. + prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not + provided, text embeddings will be generated from `prompt` input argument. + negative_prompt_embeds (`torch.FloatTensor`, *optional*): + Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt + weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input + argument. + output_type (`str`, *optional*, defaults to `"pil"`): + The output format of the generate image. Choose between + [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. + return_dict (`bool`, *optional*, defaults to `True`): + Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a + plain tuple. + callback (`Callable`, *optional*): + A function that will be called every `callback_steps` steps during inference. The function will be + called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. + callback_steps (`int`, *optional*, defaults to 1): + The frequency at which the `callback` function will be called. If not specified, the callback will be + called at every step. + cross_attention_kwargs (`dict`, *optional*): + A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under + `self.processor` in + [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). + controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 0.5): + The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added + to the residual in the original unet. If multiple ControlNets are specified in init, you can set the + corresponding scale as a list. Note that by default, we use a smaller conditioning scale for inpainting + than for [`~StableDiffusionControlNetPipeline.__call__`]. + guess_mode (`bool`, *optional*, defaults to `False`): + In this mode, the ControlNet encoder will try best to recognize the content of the input image even if + you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended. + control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): + The percentage of total steps at which the controlnet starts applying. + control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): + The percentage of total steps at which the controlnet stops applying. + + Examples: + + Returns: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: + [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. + When returning a tuple, the first element is a list with the generated images, and the second element is a + list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" + (nsfw) content, according to the `safety_checker`. + """ + controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet + + # 0. Default height and width to unet + height, width = self._default_height_width(height, width, image) + + prompt = promptA + negative_prompt = negative_promptA + + # align format for control guidance + if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): + control_guidance_start = len(control_guidance_end) * [control_guidance_start] + elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): + control_guidance_end = len(control_guidance_start) * [control_guidance_end] + elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): + mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1 + control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [ + control_guidance_end + ] + + # 1. Check inputs. Raise error if not correct + self.check_inputs( + prompt, + control_image, + height, + width, + callback_steps, + negative_prompt, + prompt_embeds, + negative_prompt_embeds, + controlnet_conditioning_scale, + control_guidance_start, + control_guidance_end, + ) + + # 2. Define call parameters + if prompt is not None and isinstance(prompt, str): + batch_size = 1 + elif prompt is not None and isinstance(prompt, list): + batch_size = len(prompt) + else: + batch_size = prompt_embeds.shape[0] + + device = self._execution_device + # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) + # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` + # corresponds to doing no classifier free guidance. + do_classifier_free_guidance = guidance_scale > 1.0 + + if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): + controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets) + + global_pool_conditions = ( + controlnet.config.global_pool_conditions + if isinstance(controlnet, ControlNetModel) + else controlnet.nets[0].config.global_pool_conditions + ) + guess_mode = guess_mode or global_pool_conditions + + # 3. Encode input prompt + text_encoder_lora_scale = ( + cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None + ) + prompt_embeds = self._encode_prompt( + promptA, + promptB, + tradoff, + device, + num_images_per_prompt, + do_classifier_free_guidance, + negative_promptA, + negative_promptB, + tradoff_nag, + prompt_embeds=prompt_embeds, + negative_prompt_embeds=negative_prompt_embeds, + lora_scale=text_encoder_lora_scale, + ) + + # 4. Prepare image + if isinstance(controlnet, ControlNetModel): + control_image = self.prepare_control_image( + image=control_image, + width=width, + height=height, + batch_size=batch_size * num_images_per_prompt, + num_images_per_prompt=num_images_per_prompt, + device=device, + dtype=controlnet.dtype, + do_classifier_free_guidance=do_classifier_free_guidance, + guess_mode=guess_mode, + ) + elif isinstance(controlnet, MultiControlNetModel): + control_images = [] + + for control_image_ in control_image: + control_image_ = self.prepare_control_image( + image=control_image_, + width=width, + height=height, + batch_size=batch_size * num_images_per_prompt, + num_images_per_prompt=num_images_per_prompt, + device=device, + dtype=controlnet.dtype, + do_classifier_free_guidance=do_classifier_free_guidance, + guess_mode=guess_mode, + ) + + control_images.append(control_image_) + + control_image = control_images + else: + assert False + + # 4. Preprocess mask and image - resizes image and mask w.r.t height and width + mask, masked_image, init_image = prepare_mask_and_masked_image( + image, mask_image, height, width, return_image=True + ) + + # 5. Prepare timesteps + self.scheduler.set_timesteps(num_inference_steps, device=device) + timesteps, num_inference_steps = self.get_timesteps( + num_inference_steps=num_inference_steps, strength=strength, device=device + ) + # at which timestep to set the initial noise (n.b. 50% if strength is 0.5) + latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) + # create a boolean to check if the strength is set to 1. if so then initialise the latents with pure noise + is_strength_max = strength == 1.0 + + # 6. Prepare latent variables + num_channels_latents = self.vae.config.latent_channels + num_channels_unet = self.unet.config.in_channels + return_image_latents = num_channels_unet == 4 + latents_outputs = self.prepare_latents( + batch_size * num_images_per_prompt, + num_channels_latents, + height, + width, + prompt_embeds.dtype, + device, + generator, + latents, + image=init_image, + timestep=latent_timestep, + is_strength_max=is_strength_max, + return_noise=True, + return_image_latents=return_image_latents, + ) + + if return_image_latents: + latents, noise, image_latents = latents_outputs + else: + latents, noise = latents_outputs + + # 7. Prepare mask latent variables + mask, masked_image_latents = self.prepare_mask_latents( + mask, + masked_image, + batch_size * num_images_per_prompt, + height, + width, + prompt_embeds.dtype, + device, + generator, + do_classifier_free_guidance, + ) + + # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline + extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) + + # 7.1 Create tensor stating which controlnets to keep + controlnet_keep = [] + for i in range(len(timesteps)): + keeps = [ + 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) + for s, e in zip(control_guidance_start, control_guidance_end) + ] + controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps) + + # 8. Denoising loop + num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order + with self.progress_bar(total=num_inference_steps) as progress_bar: + for i, t in enumerate(timesteps): + # expand the latents if we are doing classifier free guidance + latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents + latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) + + # controlnet(s) inference + if guess_mode and do_classifier_free_guidance: + # Infer ControlNet only for the conditional batch. + control_model_input = latents + control_model_input = self.scheduler.scale_model_input(control_model_input, t) + controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] + else: + control_model_input = latent_model_input + controlnet_prompt_embeds = prompt_embeds + + if isinstance(controlnet_keep[i], list): + cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] + else: + controlnet_cond_scale = controlnet_conditioning_scale + if isinstance(controlnet_cond_scale, list): + controlnet_cond_scale = controlnet_cond_scale[0] + cond_scale = controlnet_cond_scale * controlnet_keep[i] + + down_block_res_samples, mid_block_res_sample = self.controlnet( + control_model_input, + t, + encoder_hidden_states=controlnet_prompt_embeds, + controlnet_cond=control_image, + conditioning_scale=cond_scale, + guess_mode=guess_mode, + return_dict=False, + ) + + if guess_mode and do_classifier_free_guidance: + # Infered ControlNet only for the conditional batch. + # To apply the output of ControlNet to both the unconditional and conditional batches, + # add 0 to the unconditional batch to keep it unchanged. + down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] + mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample]) + + # predict the noise residual + if num_channels_unet == 9: + latent_model_input = torch.cat([latent_model_input, mask, masked_image_latents], dim=1) + + noise_pred = self.unet( + latent_model_input, + t, + encoder_hidden_states=prompt_embeds, + cross_attention_kwargs=cross_attention_kwargs, + down_block_additional_residuals=down_block_res_samples, + mid_block_additional_residual=mid_block_res_sample, + return_dict=False, + )[0] + + # perform guidance + if do_classifier_free_guidance: + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) + + # compute the previous noisy sample x_t -> x_t-1 + latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] + + if num_channels_unet == 4: + init_latents_proper = image_latents[:1] + init_mask = mask[:1] + + if i < len(timesteps) - 1: + noise_timestep = timesteps[i + 1] + init_latents_proper = self.scheduler.add_noise( + init_latents_proper, noise, torch.tensor([noise_timestep]) + ) + + latents = (1 - init_mask) * init_latents_proper + init_mask * latents + + # call the callback, if provided + if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): + progress_bar.update() + if callback is not None and i % callback_steps == 0: + callback(i, t, latents) + + # If we do sequential model offloading, let's offload unet and controlnet + # manually for max memory savings + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.unet.to("cpu") + self.controlnet.to("cpu") + torch.cuda.empty_cache() + + if not output_type == "latent": + image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] + image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) + else: + image = latents + has_nsfw_concept = None + + if has_nsfw_concept is None: + do_denormalize = [True] * image.shape[0] + else: + do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] + + image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) + + # Offload last model to CPU + if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: + self.final_offload_hook.offload() + + if not return_dict: + return (image, has_nsfw_concept) + + return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) diff --git a/py/iopaint/model/power_paint/power_paint.py b/py/iopaint/model/power_paint/power_paint.py new file mode 100644 index 0000000..f17a5a3 --- /dev/null +++ b/py/iopaint/model/power_paint/power_paint.py @@ -0,0 +1,101 @@ +from PIL import Image +import PIL.Image +import cv2 +import torch +from loguru import logger + +from ..base import DiffusionInpaintModel +from ..helper.cpu_text_encoder import CPUTextEncoderWrapper +from ..utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) +from iopaint.schema import InpaintRequest +from .powerpaint_tokenizer import add_task_to_prompt +from ...const import POWERPAINT_NAME + + +class PowerPaint(DiffusionInpaintModel): + name = POWERPAINT_NAME + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdv1-5" + + def init_model(self, device: torch.device, **kwargs): + from .pipeline_powerpaint import StableDiffusionInpaintPipeline + from .powerpaint_tokenizer import PowerPaintTokenizer + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + model_kwargs = {"local_files_only": is_local_files_only(**kwargs)} + if kwargs["disable_nsfw"] or kwargs.get("cpu_offload", False): + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + self.model = handle_from_pretrained_exceptions( + StableDiffusionInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.name, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + self.model.tokenizer = PowerPaintTokenizer(self.model.tokenizer) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + promptA, promptB, negative_promptA, negative_promptB = add_task_to_prompt( + config.prompt, config.negative_prompt, config.powerpaint_task + ) + + output = self.model( + image=PIL.Image.fromarray(image), + promptA=promptA, + promptB=promptB, + tradoff=config.fitting_degree, + tradoff_nag=config.fitting_degree, + negative_promptA=negative_promptA, + negative_promptB=negative_promptB, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + callback_steps=1, + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/power_paint/powerpaint_tokenizer.py b/py/iopaint/model/power_paint/powerpaint_tokenizer.py new file mode 100644 index 0000000..39d5cb7 --- /dev/null +++ b/py/iopaint/model/power_paint/powerpaint_tokenizer.py @@ -0,0 +1,540 @@ +import torch +import torch.nn as nn +import copy +import random +from typing import Any, List, Optional, Union +from transformers import CLIPTokenizer + +from iopaint.schema import PowerPaintTask + + +def add_task_to_prompt(prompt, negative_prompt, task: PowerPaintTask): + if task == PowerPaintTask.object_remove: + promptA = prompt + " P_ctxt" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + " P_obj" + negative_promptB = negative_prompt + " P_obj" + elif task == PowerPaintTask.shape_guided: + promptA = prompt + " P_shape" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + negative_promptB = negative_prompt + elif task == PowerPaintTask.outpainting: + promptA = prompt + " P_ctxt" + promptB = prompt + " P_ctxt" + negative_promptA = negative_prompt + " P_obj" + negative_promptB = negative_prompt + " P_obj" + else: + promptA = prompt + " P_obj" + promptB = prompt + " P_obj" + negative_promptA = negative_prompt + negative_promptB = negative_prompt + + return promptA, promptB, negative_promptA, negative_promptB + + +class PowerPaintTokenizer: + def __init__(self, tokenizer: CLIPTokenizer): + self.wrapped = tokenizer + self.token_map = {} + placeholder_tokens = ["P_ctxt", "P_shape", "P_obj"] + num_vec_per_token = 10 + for placeholder_token in placeholder_tokens: + output = [] + for i in range(num_vec_per_token): + ith_token = placeholder_token + f"_{i}" + output.append(ith_token) + self.token_map[placeholder_token] = output + + def __getattr__(self, name: str) -> Any: + if name == "wrapped": + return super().__getattr__("wrapped") + + try: + return getattr(self.wrapped, name) + except AttributeError: + try: + return super().__getattr__(name) + except AttributeError: + raise AttributeError( + "'name' cannot be found in both " + f"'{self.__class__.__name__}' and " + f"'{self.__class__.__name__}.tokenizer'." + ) + + def try_adding_tokens(self, tokens: Union[str, List[str]], *args, **kwargs): + """Attempt to add tokens to the tokenizer. + + Args: + tokens (Union[str, List[str]]): The tokens to be added. + """ + num_added_tokens = self.wrapped.add_tokens(tokens, *args, **kwargs) + assert num_added_tokens != 0, ( + f"The tokenizer already contains the token {tokens}. Please pass " + "a different `placeholder_token` that is not already in the " + "tokenizer." + ) + + def get_token_info(self, token: str) -> dict: + """Get the information of a token, including its start and end index in + the current tokenizer. + + Args: + token (str): The token to be queried. + + Returns: + dict: The information of the token, including its start and end + index in current tokenizer. + """ + token_ids = self.__call__(token).input_ids + start, end = token_ids[1], token_ids[-2] + 1 + return {"name": token, "start": start, "end": end} + + def add_placeholder_token( + self, placeholder_token: str, *args, num_vec_per_token: int = 1, **kwargs + ): + """Add placeholder tokens to the tokenizer. + + Args: + placeholder_token (str): The placeholder token to be added. + num_vec_per_token (int, optional): The number of vectors of + the added placeholder token. + *args, **kwargs: The arguments for `self.wrapped.add_tokens`. + """ + output = [] + if num_vec_per_token == 1: + self.try_adding_tokens(placeholder_token, *args, **kwargs) + output.append(placeholder_token) + else: + output = [] + for i in range(num_vec_per_token): + ith_token = placeholder_token + f"_{i}" + self.try_adding_tokens(ith_token, *args, **kwargs) + output.append(ith_token) + + for token in self.token_map: + if token in placeholder_token: + raise ValueError( + f"The tokenizer already has placeholder token {token} " + f"that can get confused with {placeholder_token} " + "keep placeholder tokens independent" + ) + self.token_map[placeholder_token] = output + + def replace_placeholder_tokens_in_text( + self, + text: Union[str, List[str]], + vector_shuffle: bool = False, + prop_tokens_to_load: float = 1.0, + ) -> Union[str, List[str]]: + """Replace the keywords in text with placeholder tokens. This function + will be called in `self.__call__` and `self.encode`. + + Args: + text (Union[str, List[str]]): The text to be processed. + vector_shuffle (bool, optional): Whether to shuffle the vectors. + Defaults to False. + prop_tokens_to_load (float, optional): The proportion of tokens to + be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0. + + Returns: + Union[str, List[str]]: The processed text. + """ + if isinstance(text, list): + output = [] + for i in range(len(text)): + output.append( + self.replace_placeholder_tokens_in_text( + text[i], vector_shuffle=vector_shuffle + ) + ) + return output + + for placeholder_token in self.token_map: + if placeholder_token in text: + tokens = self.token_map[placeholder_token] + tokens = tokens[: 1 + int(len(tokens) * prop_tokens_to_load)] + if vector_shuffle: + tokens = copy.copy(tokens) + random.shuffle(tokens) + text = text.replace(placeholder_token, " ".join(tokens)) + return text + + def replace_text_with_placeholder_tokens( + self, text: Union[str, List[str]] + ) -> Union[str, List[str]]: + """Replace the placeholder tokens in text with the original keywords. + This function will be called in `self.decode`. + + Args: + text (Union[str, List[str]]): The text to be processed. + + Returns: + Union[str, List[str]]: The processed text. + """ + if isinstance(text, list): + output = [] + for i in range(len(text)): + output.append(self.replace_text_with_placeholder_tokens(text[i])) + return output + + for placeholder_token, tokens in self.token_map.items(): + merged_tokens = " ".join(tokens) + if merged_tokens in text: + text = text.replace(merged_tokens, placeholder_token) + return text + + def __call__( + self, + text: Union[str, List[str]], + *args, + vector_shuffle: bool = False, + prop_tokens_to_load: float = 1.0, + **kwargs, + ): + """The call function of the wrapper. + + Args: + text (Union[str, List[str]]): The text to be tokenized. + vector_shuffle (bool, optional): Whether to shuffle the vectors. + Defaults to False. + prop_tokens_to_load (float, optional): The proportion of tokens to + be loaded. If 1.0, all tokens will be loaded. Defaults to 1.0 + *args, **kwargs: The arguments for `self.wrapped.__call__`. + """ + replaced_text = self.replace_placeholder_tokens_in_text( + text, vector_shuffle=vector_shuffle, prop_tokens_to_load=prop_tokens_to_load + ) + + return self.wrapped.__call__(replaced_text, *args, **kwargs) + + def encode(self, text: Union[str, List[str]], *args, **kwargs): + """Encode the passed text to token index. + + Args: + text (Union[str, List[str]]): The text to be encode. + *args, **kwargs: The arguments for `self.wrapped.__call__`. + """ + replaced_text = self.replace_placeholder_tokens_in_text(text) + return self.wrapped(replaced_text, *args, **kwargs) + + def decode( + self, token_ids, return_raw: bool = False, *args, **kwargs + ) -> Union[str, List[str]]: + """Decode the token index to text. + + Args: + token_ids: The token index to be decoded. + return_raw: Whether keep the placeholder token in the text. + Defaults to False. + *args, **kwargs: The arguments for `self.wrapped.decode`. + + Returns: + Union[str, List[str]]: The decoded text. + """ + text = self.wrapped.decode(token_ids, *args, **kwargs) + if return_raw: + return text + replaced_text = self.replace_text_with_placeholder_tokens(text) + return replaced_text + + +class EmbeddingLayerWithFixes(nn.Module): + """The revised embedding layer to support external embeddings. This design + of this class is inspired by https://github.com/AUTOMATIC1111/stable- + diffusion-webui/blob/22bcc7be428c94e9408f589966c2040187245d81/modules/sd_hi + jack.py#L224 # noqa. + + Args: + wrapped (nn.Emebdding): The embedding layer to be wrapped. + external_embeddings (Union[dict, List[dict]], optional): The external + embeddings added to this layer. Defaults to None. + """ + + def __init__( + self, + wrapped: nn.Embedding, + external_embeddings: Optional[Union[dict, List[dict]]] = None, + ): + super().__init__() + self.wrapped = wrapped + self.num_embeddings = wrapped.weight.shape[0] + + self.external_embeddings = [] + if external_embeddings: + self.add_embeddings(external_embeddings) + + self.trainable_embeddings = nn.ParameterDict() + + @property + def weight(self): + """Get the weight of wrapped embedding layer.""" + return self.wrapped.weight + + def check_duplicate_names(self, embeddings: List[dict]): + """Check whether duplicate names exist in list of 'external + embeddings'. + + Args: + embeddings (List[dict]): A list of embedding to be check. + """ + names = [emb["name"] for emb in embeddings] + assert len(names) == len(set(names)), ( + "Found duplicated names in 'external_embeddings'. Name list: " f"'{names}'" + ) + + def check_ids_overlap(self, embeddings): + """Check whether overlap exist in token ids of 'external_embeddings'. + + Args: + embeddings (List[dict]): A list of embedding to be check. + """ + ids_range = [[emb["start"], emb["end"], emb["name"]] for emb in embeddings] + ids_range.sort() # sort by 'start' + # check if 'end' has overlapping + for idx in range(len(ids_range) - 1): + name1, name2 = ids_range[idx][-1], ids_range[idx + 1][-1] + assert ids_range[idx][1] <= ids_range[idx + 1][0], ( + f"Found ids overlapping between embeddings '{name1}' " f"and '{name2}'." + ) + + def add_embeddings(self, embeddings: Optional[Union[dict, List[dict]]]): + """Add external embeddings to this layer. + + Use case: + + >>> 1. Add token to tokenizer and get the token id. + >>> tokenizer = TokenizerWrapper('openai/clip-vit-base-patch32') + >>> # 'how much' in kiswahili + >>> tokenizer.add_placeholder_tokens('ngapi', num_vec_per_token=4) + >>> + >>> 2. Add external embeddings to the model. + >>> new_embedding = { + >>> 'name': 'ngapi', # 'how much' in kiswahili + >>> 'embedding': torch.ones(1, 15) * 4, + >>> 'start': tokenizer.get_token_info('kwaheri')['start'], + >>> 'end': tokenizer.get_token_info('kwaheri')['end'], + >>> 'trainable': False # if True, will registry as a parameter + >>> } + >>> embedding_layer = nn.Embedding(10, 15) + >>> embedding_layer_wrapper = EmbeddingLayerWithFixes(embedding_layer) + >>> embedding_layer_wrapper.add_embeddings(new_embedding) + >>> + >>> 3. Forward tokenizer and embedding layer! + >>> input_text = ['hello, ngapi!', 'hello my friend, ngapi?'] + >>> input_ids = tokenizer( + >>> input_text, padding='max_length', truncation=True, + >>> return_tensors='pt')['input_ids'] + >>> out_feat = embedding_layer_wrapper(input_ids) + >>> + >>> 4. Let's validate the result! + >>> assert (out_feat[0, 3: 7] == 2.3).all() + >>> assert (out_feat[2, 5: 9] == 2.3).all() + + Args: + embeddings (Union[dict, list[dict]]): The external embeddings to + be added. Each dict must contain the following 4 fields: 'name' + (the name of this embedding), 'embedding' (the embedding + tensor), 'start' (the start token id of this embedding), 'end' + (the end token id of this embedding). For example: + `{name: NAME, start: START, end: END, embedding: torch.Tensor}` + """ + if isinstance(embeddings, dict): + embeddings = [embeddings] + + self.external_embeddings += embeddings + self.check_duplicate_names(self.external_embeddings) + self.check_ids_overlap(self.external_embeddings) + + # set for trainable + added_trainable_emb_info = [] + for embedding in embeddings: + trainable = embedding.get("trainable", False) + if trainable: + name = embedding["name"] + embedding["embedding"] = torch.nn.Parameter(embedding["embedding"]) + self.trainable_embeddings[name] = embedding["embedding"] + added_trainable_emb_info.append(name) + + added_emb_info = [emb["name"] for emb in embeddings] + added_emb_info = ", ".join(added_emb_info) + print(f"Successfully add external embeddings: {added_emb_info}.", "current") + + if added_trainable_emb_info: + added_trainable_emb_info = ", ".join(added_trainable_emb_info) + print( + "Successfully add trainable external embeddings: " + f"{added_trainable_emb_info}", + "current", + ) + + def replace_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: + """Replace external input ids to 0. + + Args: + input_ids (torch.Tensor): The input ids to be replaced. + + Returns: + torch.Tensor: The replaced input ids. + """ + input_ids_fwd = input_ids.clone() + input_ids_fwd[input_ids_fwd >= self.num_embeddings] = 0 + return input_ids_fwd + + def replace_embeddings( + self, input_ids: torch.Tensor, embedding: torch.Tensor, external_embedding: dict + ) -> torch.Tensor: + """Replace external embedding to the embedding layer. Noted that, in + this function we use `torch.cat` to avoid inplace modification. + + Args: + input_ids (torch.Tensor): The original token ids. Shape like + [LENGTH, ]. + embedding (torch.Tensor): The embedding of token ids after + `replace_input_ids` function. + external_embedding (dict): The external embedding to be replaced. + + Returns: + torch.Tensor: The replaced embedding. + """ + new_embedding = [] + + name = external_embedding["name"] + start = external_embedding["start"] + end = external_embedding["end"] + target_ids_to_replace = [i for i in range(start, end)] + ext_emb = external_embedding["embedding"] + + # do not need to replace + if not (input_ids == start).any(): + return embedding + + # start replace + s_idx, e_idx = 0, 0 + while e_idx < len(input_ids): + if input_ids[e_idx] == start: + if e_idx != 0: + # add embedding do not need to replace + new_embedding.append(embedding[s_idx:e_idx]) + + # check if the next embedding need to replace is valid + actually_ids_to_replace = [ + int(i) for i in input_ids[e_idx : e_idx + end - start] + ] + assert actually_ids_to_replace == target_ids_to_replace, ( + f"Invalid 'input_ids' in position: {s_idx} to {e_idx}. " + f"Expect '{target_ids_to_replace}' for embedding " + f"'{name}' but found '{actually_ids_to_replace}'." + ) + + new_embedding.append(ext_emb) + + s_idx = e_idx + end - start + e_idx = s_idx + 1 + else: + e_idx += 1 + + if e_idx == len(input_ids): + new_embedding.append(embedding[s_idx:e_idx]) + + return torch.cat(new_embedding, dim=0) + + def forward( + self, input_ids: torch.Tensor, external_embeddings: Optional[List[dict]] = None + ): + """The forward function. + + Args: + input_ids (torch.Tensor): The token ids shape like [bz, LENGTH] or + [LENGTH, ]. + external_embeddings (Optional[List[dict]]): The external + embeddings. If not passed, only `self.external_embeddings` + will be used. Defaults to None. + + input_ids: shape like [bz, LENGTH] or [LENGTH]. + """ + assert input_ids.ndim in [1, 2] + if input_ids.ndim == 1: + input_ids = input_ids.unsqueeze(0) + + if external_embeddings is None and not self.external_embeddings: + return self.wrapped(input_ids) + + input_ids_fwd = self.replace_input_ids(input_ids) + inputs_embeds = self.wrapped(input_ids_fwd) + + vecs = [] + + if external_embeddings is None: + external_embeddings = [] + elif isinstance(external_embeddings, dict): + external_embeddings = [external_embeddings] + embeddings = self.external_embeddings + external_embeddings + + for input_id, embedding in zip(input_ids, inputs_embeds): + new_embedding = embedding + for external_embedding in embeddings: + new_embedding = self.replace_embeddings( + input_id, new_embedding, external_embedding + ) + vecs.append(new_embedding) + + return torch.stack(vecs) + + +def add_tokens( + tokenizer, + text_encoder, + placeholder_tokens: list, + initialize_tokens: list = None, + num_vectors_per_token: int = 1, +): + """Add token for training. + + # TODO: support add tokens as dict, then we can load pretrained tokens. + """ + if initialize_tokens is not None: + assert len(initialize_tokens) == len( + placeholder_tokens + ), "placeholder_token should be the same length as initialize_token" + for ii in range(len(placeholder_tokens)): + tokenizer.add_placeholder_token( + placeholder_tokens[ii], num_vec_per_token=num_vectors_per_token + ) + + # text_encoder.set_embedding_layer() + embedding_layer = text_encoder.text_model.embeddings.token_embedding + text_encoder.text_model.embeddings.token_embedding = EmbeddingLayerWithFixes( + embedding_layer + ) + embedding_layer = text_encoder.text_model.embeddings.token_embedding + + assert embedding_layer is not None, ( + "Do not support get embedding layer for current text encoder. " + "Please check your configuration." + ) + initialize_embedding = [] + if initialize_tokens is not None: + for ii in range(len(placeholder_tokens)): + init_id = tokenizer(initialize_tokens[ii]).input_ids[1] + temp_embedding = embedding_layer.weight[init_id] + initialize_embedding.append( + temp_embedding[None, ...].repeat(num_vectors_per_token, 1) + ) + else: + for ii in range(len(placeholder_tokens)): + init_id = tokenizer("a").input_ids[1] + temp_embedding = embedding_layer.weight[init_id] + len_emb = temp_embedding.shape[0] + init_weight = (torch.rand(num_vectors_per_token, len_emb) - 0.5) / 2.0 + initialize_embedding.append(init_weight) + + # initialize_embedding = torch.cat(initialize_embedding,dim=0) + + token_info_all = [] + for ii in range(len(placeholder_tokens)): + token_info = tokenizer.get_token_info(placeholder_tokens[ii]) + token_info["embedding"] = initialize_embedding[ii] + token_info["trainable"] = True + token_info_all.append(token_info) + embedding_layer.add_embeddings(token_info_all) diff --git a/py/iopaint/model/sd.py b/py/iopaint/model/sd.py new file mode 100644 index 0000000..8f42fff --- /dev/null +++ b/py/iopaint/model/sd.py @@ -0,0 +1,129 @@ +import PIL.Image +import cv2 +import torch +from loguru import logger + +from .base import DiffusionInpaintModel +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) +from iopaint.schema import InpaintRequest, ModelType + + +class SD(DiffusionInpaintModel): + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdv1-5" + + def init_model(self, device: torch.device, **kwargs): + from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + disable_nsfw_checker = kwargs["disable_nsfw"] or kwargs.get( + "cpu_offload", False + ) + if disable_nsfw_checker: + logger.info("Disable Stable Diffusion Model NSFW checker") + model_kwargs.update( + dict( + safety_checker=None, + feature_extractor=None, + requires_safety_checker=False, + ) + ) + + if self.model_info.is_single_file_diffusers: + if self.model_info.model_type == ModelType.DIFFUSERS_SD: + model_kwargs["num_in_channels"] = 4 + else: + model_kwargs["num_in_channels"] = 9 + + self.model = StableDiffusionInpaintPipeline.from_single_file( + self.model_id_or_path, + torch_dtype=torch_dtype, + load_safety_checker=not disable_nsfw_checker, + config_files=get_config_files(), + **model_kwargs, + ) + else: + self.model = handle_from_pretrained_exceptions( + StableDiffusionInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.model_id_or_path, + variant="fp16", + torch_dtype=torch_dtype, + **model_kwargs, + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output + + +class SD15(SD): + name = "runwayml/stable-diffusion-inpainting" + model_id_or_path = "runwayml/stable-diffusion-inpainting" + + +class Anything4(SD): + name = "Sanster/anything-4.0-inpainting" + model_id_or_path = "Sanster/anything-4.0-inpainting" + + +class RealisticVision14(SD): + name = "Sanster/Realistic_Vision_V1.4-inpainting" + model_id_or_path = "Sanster/Realistic_Vision_V1.4-inpainting" + + +class SD2(SD): + name = "stabilityai/stable-diffusion-2-inpainting" + model_id_or_path = "stabilityai/stable-diffusion-2-inpainting" diff --git a/py/iopaint/model/sdxl.py b/py/iopaint/model/sdxl.py new file mode 100644 index 0000000..29312b1 --- /dev/null +++ b/py/iopaint/model/sdxl.py @@ -0,0 +1,110 @@ +import os + +import PIL.Image +import cv2 +import torch +from diffusers import AutoencoderKL +from loguru import logger + +from iopaint.schema import InpaintRequest, ModelType + +from .base import DiffusionInpaintModel +from .helper.cpu_text_encoder import CPUTextEncoderWrapper +from .original_sd_configs import get_config_files +from .utils import ( + handle_from_pretrained_exceptions, + get_torch_dtype, + enable_low_mem, + is_local_files_only, +) + + +class SDXL(DiffusionInpaintModel): + name = "diffusers/stable-diffusion-xl-1.0-inpainting-0.1" + pad_mod = 8 + min_size = 512 + lcm_lora_id = "latent-consistency/lcm-lora-sdxl" + model_id_or_path = "diffusers/stable-diffusion-xl-1.0-inpainting-0.1" + + def init_model(self, device: torch.device, **kwargs): + from diffusers.pipelines import StableDiffusionXLInpaintPipeline + + use_gpu, torch_dtype = get_torch_dtype(device, kwargs.get("no_half", False)) + + if self.model_info.model_type == ModelType.DIFFUSERS_SDXL: + num_in_channels = 4 + else: + num_in_channels = 9 + + if os.path.isfile(self.model_id_or_path): + self.model = StableDiffusionXLInpaintPipeline.from_single_file( + self.model_id_or_path, + torch_dtype=torch_dtype, + num_in_channels=num_in_channels, + load_safety_checker=False, + config_files=get_config_files() + ) + else: + model_kwargs = { + **kwargs.get("pipe_components", {}), + "local_files_only": is_local_files_only(**kwargs), + } + if "vae" not in model_kwargs: + vae = AutoencoderKL.from_pretrained( + "madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch_dtype + ) + model_kwargs["vae"] = vae + self.model = handle_from_pretrained_exceptions( + StableDiffusionXLInpaintPipeline.from_pretrained, + pretrained_model_name_or_path=self.model_id_or_path, + torch_dtype=torch_dtype, + variant="fp16", + **model_kwargs + ) + + enable_low_mem(self.model, kwargs.get("low_mem", False)) + + if kwargs.get("cpu_offload", False) and use_gpu: + logger.info("Enable sequential cpu offload") + self.model.enable_sequential_cpu_offload(gpu_id=0) + else: + self.model = self.model.to(device) + if kwargs["sd_cpu_textencoder"]: + logger.info("Run Stable Diffusion TextEncoder on CPU") + self.model.text_encoder = CPUTextEncoderWrapper( + self.model.text_encoder, torch_dtype + ) + self.model.text_encoder_2 = CPUTextEncoderWrapper( + self.model.text_encoder_2, torch_dtype + ) + + self.callback = kwargs.pop("callback", None) + + def forward(self, image, mask, config: InpaintRequest): + """Input image and output image have same size + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + return: BGR IMAGE + """ + self.set_scheduler(config) + + img_h, img_w = image.shape[:2] + + output = self.model( + image=PIL.Image.fromarray(image), + prompt=config.prompt, + negative_prompt=config.negative_prompt, + mask_image=PIL.Image.fromarray(mask[:, :, -1], mode="L"), + num_inference_steps=config.sd_steps, + strength=0.999 if config.sd_strength == 1.0 else config.sd_strength, + guidance_scale=config.sd_guidance_scale, + output_type="np", + callback_on_step_end=self.callback, + height=img_h, + width=img_w, + generator=torch.manual_seed(config.sd_seed), + ).images[0] + + output = (output * 255).round().astype("uint8") + output = cv2.cvtColor(output, cv2.COLOR_RGB2BGR) + return output diff --git a/py/iopaint/model/utils.py b/py/iopaint/model/utils.py new file mode 100644 index 0000000..73465e8 --- /dev/null +++ b/py/iopaint/model/utils.py @@ -0,0 +1,1033 @@ +import gc +import math +import random +import traceback +from typing import Any + +import torch +import numpy as np +import collections +from itertools import repeat + +from diffusers import ( + DDIMScheduler, + PNDMScheduler, + LMSDiscreteScheduler, + EulerDiscreteScheduler, + EulerAncestralDiscreteScheduler, + DPMSolverMultistepScheduler, + UniPCMultistepScheduler, + LCMScheduler, + DPMSolverSinglestepScheduler, + KDPM2DiscreteScheduler, + KDPM2AncestralDiscreteScheduler, + HeunDiscreteScheduler, +) +from loguru import logger + +from iopaint.schema import SDSampler +from torch import conv2d, conv_transpose2d + + +def make_beta_schedule( + device, schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3 +): + if schedule == "linear": + betas = ( + torch.linspace( + linear_start**0.5, linear_end**0.5, n_timestep, dtype=torch.float64 + ) + ** 2 + ) + + elif schedule == "cosine": + timesteps = ( + torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s + ).to(device) + alphas = timesteps / (1 + cosine_s) * np.pi / 2 + alphas = torch.cos(alphas).pow(2).to(device) + alphas = alphas / alphas[0] + betas = 1 - alphas[1:] / alphas[:-1] + betas = np.clip(betas, a_min=0, a_max=0.999) + + elif schedule == "sqrt_linear": + betas = torch.linspace( + linear_start, linear_end, n_timestep, dtype=torch.float64 + ) + elif schedule == "sqrt": + betas = ( + torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) + ** 0.5 + ) + else: + raise ValueError(f"schedule '{schedule}' unknown.") + return betas.numpy() + + +def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True): + # select alphas for computing the variance schedule + alphas = alphacums[ddim_timesteps] + alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist()) + + # according the the formula provided in https://arxiv.org/abs/2010.02502 + sigmas = eta * np.sqrt( + (1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev) + ) + if verbose: + print( + f"Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}" + ) + print( + f"For the chosen value of eta, which is {eta}, " + f"this results in the following sigma_t schedule for ddim sampler {sigmas}" + ) + return sigmas, alphas, alphas_prev + + +def make_ddim_timesteps( + ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True +): + if ddim_discr_method == "uniform": + c = num_ddpm_timesteps // num_ddim_timesteps + ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c))) + elif ddim_discr_method == "quad": + ddim_timesteps = ( + (np.linspace(0, np.sqrt(num_ddpm_timesteps * 0.8), num_ddim_timesteps)) ** 2 + ).astype(int) + else: + raise NotImplementedError( + f'There is no ddim discretization method called "{ddim_discr_method}"' + ) + + # assert ddim_timesteps.shape[0] == num_ddim_timesteps + # add one to get the final alpha values right (the ones from first scale to data during sampling) + steps_out = ddim_timesteps + 1 + if verbose: + print(f"Selected timesteps for ddim sampler: {steps_out}") + return steps_out + + +def noise_like(shape, device, repeat=False): + repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat( + shape[0], *((1,) * (len(shape) - 1)) + ) + noise = lambda: torch.randn(shape, device=device) + return repeat_noise() if repeat else noise() + + +def timestep_embedding(device, timesteps, dim, max_period=10000, repeat_only=False): + """ + Create sinusoidal timestep embeddings. + :param timesteps: a 1-D Tensor of N indices, one per batch element. + These may be fractional. + :param dim: the dimension of the output. + :param max_period: controls the minimum frequency of the embeddings. + :return: an [N x dim] Tensor of positional embeddings. + """ + half = dim // 2 + freqs = torch.exp( + -math.log(max_period) + * torch.arange(start=0, end=half, dtype=torch.float32) + / half + ).to(device=device) + + args = timesteps[:, None].float() * freqs[None] + + embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) + if dim % 2: + embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) + return embedding + + +###### MAT and FcF ####### + + +def normalize_2nd_moment(x, dim=1): + return ( + x * (x.square().mean(dim=dim, keepdim=True) + torch.finfo(x.dtype).eps).rsqrt() + ) + + +class EasyDict(dict): + """Convenience class that behaves like a dict but allows access with the attribute syntax.""" + + def __getattr__(self, name: str) -> Any: + try: + return self[name] + except KeyError: + raise AttributeError(name) + + def __setattr__(self, name: str, value: Any) -> None: + self[name] = value + + def __delattr__(self, name: str) -> None: + del self[name] + + +def _bias_act_ref(x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None): + """Slow reference implementation of `bias_act()` using standard TensorFlow ops.""" + assert isinstance(x, torch.Tensor) + assert clamp is None or clamp >= 0 + spec = activation_funcs[act] + alpha = float(alpha if alpha is not None else spec.def_alpha) + gain = float(gain if gain is not None else spec.def_gain) + clamp = float(clamp if clamp is not None else -1) + + # Add bias. + if b is not None: + assert isinstance(b, torch.Tensor) and b.ndim == 1 + assert 0 <= dim < x.ndim + assert b.shape[0] == x.shape[dim] + x = x + b.reshape([-1 if i == dim else 1 for i in range(x.ndim)]) + + # Evaluate activation function. + alpha = float(alpha) + x = spec.func(x, alpha=alpha) + + # Scale by gain. + gain = float(gain) + if gain != 1: + x = x * gain + + # Clamp. + if clamp >= 0: + x = x.clamp(-clamp, clamp) # pylint: disable=invalid-unary-operand-type + return x + + +def bias_act( + x, b=None, dim=1, act="linear", alpha=None, gain=None, clamp=None, impl="ref" +): + r"""Fused bias and activation function. + + Adds bias `b` to activation tensor `x`, evaluates activation function `act`, + and scales the result by `gain`. Each of the steps is optional. In most cases, + the fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports first and second order gradients, + but not third order gradients. + + Args: + x: Input activation tensor. Can be of any shape. + b: Bias vector, or `None` to disable. Must be a 1D tensor of the same type + as `x`. The shape must be known, and it must match the dimension of `x` + corresponding to `dim`. + dim: The dimension in `x` corresponding to the elements of `b`. + The value of `dim` is ignored if `b` is not specified. + act: Name of the activation function to evaluate, or `"linear"` to disable. + Can be e.g. `"relu"`, `"lrelu"`, `"tanh"`, `"sigmoid"`, `"swish"`, etc. + See `activation_funcs` for a full list. `None` is not allowed. + alpha: Shape parameter for the activation function, or `None` to use the default. + gain: Scaling factor for the output tensor, or `None` to use default. + See `activation_funcs` for the default scaling of each activation function. + If unsure, consider specifying 1. + clamp: Clamp the output values to `[-clamp, +clamp]`, or `None` to disable + the clamping (default). + impl: Name of the implementation to use. Can be `"ref"` or `"cuda"` (default). + + Returns: + Tensor of the same shape and datatype as `x`. + """ + assert isinstance(x, torch.Tensor) + assert impl in ["ref", "cuda"] + return _bias_act_ref( + x=x, b=b, dim=dim, act=act, alpha=alpha, gain=gain, clamp=clamp + ) + + +def _get_filter_size(f): + if f is None: + return 1, 1 + + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + fw = f.shape[-1] + fh = f.shape[0] + + fw = int(fw) + fh = int(fh) + assert fw >= 1 and fh >= 1 + return fw, fh + + +def _get_weight_shape(w): + shape = [int(sz) for sz in w.shape] + return shape + + +def _parse_scaling(scaling): + if isinstance(scaling, int): + scaling = [scaling, scaling] + assert isinstance(scaling, (list, tuple)) + assert all(isinstance(x, int) for x in scaling) + sx, sy = scaling + assert sx >= 1 and sy >= 1 + return sx, sy + + +def _parse_padding(padding): + if isinstance(padding, int): + padding = [padding, padding] + assert isinstance(padding, (list, tuple)) + assert all(isinstance(x, int) for x in padding) + if len(padding) == 2: + padx, pady = padding + padding = [padx, padx, pady, pady] + padx0, padx1, pady0, pady1 = padding + return padx0, padx1, pady0, pady1 + + +def setup_filter( + f, + device=torch.device("cpu"), + normalize=True, + flip_filter=False, + gain=1, + separable=None, +): + r"""Convenience function to setup 2D FIR filter for `upfirdn2d()`. + + Args: + f: Torch tensor, numpy array, or python list of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), + `[]` (impulse), or + `None` (identity). + device: Result device (default: cpu). + normalize: Normalize the filter so that it retains the magnitude + for constant input signal (DC)? (default: True). + flip_filter: Flip the filter? (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + separable: Return a separable filter? (default: select automatically). + + Returns: + Float32 tensor of the shape + `[filter_height, filter_width]` (non-separable) or + `[filter_taps]` (separable). + """ + # Validate. + if f is None: + f = 1 + f = torch.as_tensor(f, dtype=torch.float32) + assert f.ndim in [0, 1, 2] + assert f.numel() > 0 + if f.ndim == 0: + f = f[np.newaxis] + + # Separable? + if separable is None: + separable = f.ndim == 1 and f.numel() >= 8 + if f.ndim == 1 and not separable: + f = f.ger(f) + assert f.ndim == (1 if separable else 2) + + # Apply normalize, flip, gain, and device. + if normalize: + f /= f.sum() + if flip_filter: + f = f.flip(list(range(f.ndim))) + f = f * (gain ** (f.ndim / 2)) + f = f.to(device=device) + return f + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable): + return x + return tuple(repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) + +activation_funcs = { + "linear": EasyDict( + func=lambda x, **_: x, + def_alpha=0, + def_gain=1, + cuda_idx=1, + ref="", + has_2nd_grad=False, + ), + "relu": EasyDict( + func=lambda x, **_: torch.nn.functional.relu(x), + def_alpha=0, + def_gain=np.sqrt(2), + cuda_idx=2, + ref="y", + has_2nd_grad=False, + ), + "lrelu": EasyDict( + func=lambda x, alpha, **_: torch.nn.functional.leaky_relu(x, alpha), + def_alpha=0.2, + def_gain=np.sqrt(2), + cuda_idx=3, + ref="y", + has_2nd_grad=False, + ), + "tanh": EasyDict( + func=lambda x, **_: torch.tanh(x), + def_alpha=0, + def_gain=1, + cuda_idx=4, + ref="y", + has_2nd_grad=True, + ), + "sigmoid": EasyDict( + func=lambda x, **_: torch.sigmoid(x), + def_alpha=0, + def_gain=1, + cuda_idx=5, + ref="y", + has_2nd_grad=True, + ), + "elu": EasyDict( + func=lambda x, **_: torch.nn.functional.elu(x), + def_alpha=0, + def_gain=1, + cuda_idx=6, + ref="y", + has_2nd_grad=True, + ), + "selu": EasyDict( + func=lambda x, **_: torch.nn.functional.selu(x), + def_alpha=0, + def_gain=1, + cuda_idx=7, + ref="y", + has_2nd_grad=True, + ), + "softplus": EasyDict( + func=lambda x, **_: torch.nn.functional.softplus(x), + def_alpha=0, + def_gain=1, + cuda_idx=8, + ref="y", + has_2nd_grad=True, + ), + "swish": EasyDict( + func=lambda x, **_: torch.sigmoid(x) * x, + def_alpha=0, + def_gain=np.sqrt(2), + cuda_idx=9, + ref="x", + has_2nd_grad=True, + ), +} + + +def upfirdn2d(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Pad, upsample, filter, and downsample a batch of 2D images. + + Performs the following sequence of operations for each channel: + + 1. Upsample the image by inserting N-1 zeros after each pixel (`up`). + + 2. Pad the image with the specified number of zeros on each side (`padding`). + Negative padding corresponds to cropping the image. + + 3. Convolve the image with the specified 2D FIR filter (`f`), shrinking it + so that the footprint of all output pixels lies within the input image. + + 4. Downsample the image by keeping every Nth pixel (`down`). + + This sequence of operations bears close resemblance to scipy.signal.upfirdn(). + The fused op is considerably more efficient than performing the same calculation + using standard PyTorch ops. It supports gradients of arbitrary order. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # assert isinstance(x, torch.Tensor) + # assert impl in ['ref', 'cuda'] + return _upfirdn2d_ref( + x, f, up=up, down=down, padding=padding, flip_filter=flip_filter, gain=gain + ) + + +def _upfirdn2d_ref(x, f, up=1, down=1, padding=0, flip_filter=False, gain=1): + """Slow reference implementation of `upfirdn2d()` using standard PyTorch ops.""" + # Validate arguments. + assert isinstance(x, torch.Tensor) and x.ndim == 4 + if f is None: + f = torch.ones([1, 1], dtype=torch.float32, device=x.device) + assert isinstance(f, torch.Tensor) and f.ndim in [1, 2] + assert not f.requires_grad + batch_size, num_channels, in_height, in_width = x.shape + # upx, upy = _parse_scaling(up) + # downx, downy = _parse_scaling(down) + + upx, upy = up, up + downx, downy = down, down + + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding[0], padding[1], padding[2], padding[3] + + # Upsample by inserting zeros. + x = x.reshape([batch_size, num_channels, in_height, 1, in_width, 1]) + x = torch.nn.functional.pad(x, [0, upx - 1, 0, 0, 0, upy - 1]) + x = x.reshape([batch_size, num_channels, in_height * upy, in_width * upx]) + + # Pad or crop. + x = torch.nn.functional.pad( + x, [max(padx0, 0), max(padx1, 0), max(pady0, 0), max(pady1, 0)] + ) + x = x[ + :, + :, + max(-pady0, 0) : x.shape[2] - max(-pady1, 0), + max(-padx0, 0) : x.shape[3] - max(-padx1, 0), + ] + + # Setup filter. + f = f * (gain ** (f.ndim / 2)) + f = f.to(x.dtype) + if not flip_filter: + f = f.flip(list(range(f.ndim))) + + # Convolve with the filter. + f = f[np.newaxis, np.newaxis].repeat([num_channels, 1] + [1] * f.ndim) + if f.ndim == 4: + x = conv2d(input=x, weight=f, groups=num_channels) + else: + x = conv2d(input=x, weight=f.unsqueeze(2), groups=num_channels) + x = conv2d(input=x, weight=f.unsqueeze(3), groups=num_channels) + + # Downsample by throwing away pixels. + x = x[:, :, ::downy, ::downx] + return x + + +def downsample2d(x, f, down=2, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Downsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a fraction of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + down: Integer downsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the input. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + downx, downy = _parse_scaling(down) + # padx0, padx1, pady0, pady1 = _parse_padding(padding) + padx0, padx1, pady0, pady1 = padding, padding, padding, padding + + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw - downx + 1) // 2, + padx1 + (fw - downx) // 2, + pady0 + (fh - downy + 1) // 2, + pady1 + (fh - downy) // 2, + ] + return upfirdn2d( + x, f, down=down, padding=p, flip_filter=flip_filter, gain=gain, impl=impl + ) + + +def upsample2d(x, f, up=2, padding=0, flip_filter=False, gain=1, impl="cuda"): + r"""Upsample a batch of 2D images using the given 2D FIR filter. + + By default, the result is padded so that its shape is a multiple of the input. + User-specified padding is applied on top of that, with negative values + indicating cropping. Pixels outside the image are assumed to be zero. + + Args: + x: Float32/float64/float16 input tensor of the shape + `[batch_size, num_channels, in_height, in_width]`. + f: Float32 FIR filter of the shape + `[filter_height, filter_width]` (non-separable), + `[filter_taps]` (separable), or + `None` (identity). + up: Integer upsampling factor. Can be a single int or a list/tuple + `[x, y]` (default: 1). + padding: Padding with respect to the output. Can be a single number or a + list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + flip_filter: False = convolution, True = correlation (default: False). + gain: Overall scaling factor for signal magnitude (default: 1). + impl: Implementation to use. Can be `'ref'` or `'cuda'` (default: `'cuda'`). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + upx, upy = _parse_scaling(up) + # upx, upy = up, up + padx0, padx1, pady0, pady1 = _parse_padding(padding) + # padx0, padx1, pady0, pady1 = padding, padding, padding, padding + fw, fh = _get_filter_size(f) + p = [ + padx0 + (fw + upx - 1) // 2, + padx1 + (fw - upx) // 2, + pady0 + (fh + upy - 1) // 2, + pady1 + (fh - upy) // 2, + ] + return upfirdn2d( + x, + f, + up=up, + padding=p, + flip_filter=flip_filter, + gain=gain * upx * upy, + impl=impl, + ) + + +class MinibatchStdLayer(torch.nn.Module): + def __init__(self, group_size, num_channels=1): + super().__init__() + self.group_size = group_size + self.num_channels = num_channels + + def forward(self, x): + N, C, H, W = x.shape + G = ( + torch.min(torch.as_tensor(self.group_size), torch.as_tensor(N)) + if self.group_size is not None + else N + ) + F = self.num_channels + c = C // F + + y = x.reshape( + G, -1, F, c, H, W + ) # [GnFcHW] Split minibatch N into n groups of size G, and channels C into F groups of size c. + y = y - y.mean(dim=0) # [GnFcHW] Subtract mean over group. + y = y.square().mean(dim=0) # [nFcHW] Calc variance over group. + y = (y + 1e-8).sqrt() # [nFcHW] Calc stddev over group. + y = y.mean(dim=[2, 3, 4]) # [nF] Take average over channels and pixels. + y = y.reshape(-1, F, 1, 1) # [nF11] Add missing dimensions. + y = y.repeat(G, 1, H, W) # [NFHW] Replicate over group and pixels. + x = torch.cat([x, y], dim=1) # [NCHW] Append to input as new channels. + return x + + +class FullyConnectedLayer(torch.nn.Module): + def __init__( + self, + in_features, # Number of input features. + out_features, # Number of output features. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + lr_multiplier=1, # Learning rate multiplier. + bias_init=0, # Initial value for the additive bias. + ): + super().__init__() + self.weight = torch.nn.Parameter( + torch.randn([out_features, in_features]) / lr_multiplier + ) + self.bias = ( + torch.nn.Parameter(torch.full([out_features], np.float32(bias_init))) + if bias + else None + ) + self.activation = activation + + self.weight_gain = lr_multiplier / np.sqrt(in_features) + self.bias_gain = lr_multiplier + + def forward(self, x): + w = self.weight * self.weight_gain + b = self.bias + if b is not None and self.bias_gain != 1: + b = b * self.bias_gain + + if self.activation == "linear" and b is not None: + # out = torch.addmm(b.unsqueeze(0), x, w.t()) + x = x.matmul(w.t()) + out = x + b.reshape([-1 if i == x.ndim - 1 else 1 for i in range(x.ndim)]) + else: + x = x.matmul(w.t()) + out = bias_act(x, b, act=self.activation, dim=x.ndim - 1) + return out + + +def _conv2d_wrapper( + x, w, stride=1, padding=0, groups=1, transpose=False, flip_weight=True +): + """Wrapper for the underlying `conv2d()` and `conv_transpose2d()` implementations.""" + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + + # Flip weight if requested. + if ( + not flip_weight + ): # conv2d() actually performs correlation (flip_weight=True) not convolution (flip_weight=False). + w = w.flip([2, 3]) + + # Workaround performance pitfall in cuDNN 8.0.5, triggered when using + # 1x1 kernel + memory_format=channels_last + less than 64 channels. + if ( + kw == 1 + and kh == 1 + and stride == 1 + and padding in [0, [0, 0], (0, 0)] + and not transpose + ): + if x.stride()[1] == 1 and min(out_channels, in_channels_per_group) < 64: + if out_channels <= 4 and groups == 1: + in_shape = x.shape + x = w.squeeze(3).squeeze(2) @ x.reshape( + [in_shape[0], in_channels_per_group, -1] + ) + x = x.reshape([in_shape[0], out_channels, in_shape[2], in_shape[3]]) + else: + x = x.to(memory_format=torch.contiguous_format) + w = w.to(memory_format=torch.contiguous_format) + x = conv2d(x, w, groups=groups) + return x.to(memory_format=torch.channels_last) + + # Otherwise => execute using conv2d_gradfix. + op = conv_transpose2d if transpose else conv2d + return op(x, w, stride=stride, padding=padding, groups=groups) + + +def conv2d_resample( + x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False +): + r"""2D convolution with optional up/downsampling. + + Padding is performed only once at the beginning, not between the operations. + + Args: + x: Input tensor of shape + `[batch_size, in_channels, in_height, in_width]`. + w: Weight tensor of shape + `[out_channels, in_channels//groups, kernel_height, kernel_width]`. + f: Low-pass filter for up/downsampling. Must be prepared beforehand by + calling setup_filter(). None = identity (default). + up: Integer upsampling factor (default: 1). + down: Integer downsampling factor (default: 1). + padding: Padding with respect to the upsampled image. Can be a single number + or a list/tuple `[x, y]` or `[x_before, x_after, y_before, y_after]` + (default: 0). + groups: Split input channels into N groups (default: 1). + flip_weight: False = convolution, True = correlation (default: True). + flip_filter: False = convolution, True = correlation (default: False). + + Returns: + Tensor of the shape `[batch_size, num_channels, out_height, out_width]`. + """ + # Validate arguments. + assert isinstance(x, torch.Tensor) and (x.ndim == 4) + assert isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype) + assert f is None or (isinstance(f, torch.Tensor) and f.ndim in [1, 2]) + assert isinstance(up, int) and (up >= 1) + assert isinstance(down, int) and (down >= 1) + # assert isinstance(groups, int) and (groups >= 1), f"!!!!!! groups: {groups} isinstance(groups, int) {isinstance(groups, int)} {type(groups)}" + out_channels, in_channels_per_group, kh, kw = _get_weight_shape(w) + fw, fh = _get_filter_size(f) + # px0, px1, py0, py1 = _parse_padding(padding) + px0, px1, py0, py1 = padding, padding, padding, padding + + # Adjust padding to account for up/downsampling. + if up > 1: + px0 += (fw + up - 1) // 2 + px1 += (fw - up) // 2 + py0 += (fh + up - 1) // 2 + py1 += (fh - up) // 2 + if down > 1: + px0 += (fw - down + 1) // 2 + px1 += (fw - down) // 2 + py0 += (fh - down + 1) // 2 + py1 += (fh - down) // 2 + + # Fast path: 1x1 convolution with downsampling only => downsample first, then convolve. + if kw == 1 and kh == 1 and (down > 1 and up == 1): + x = upfirdn2d( + x=x, f=f, down=down, padding=[px0, px1, py0, py1], flip_filter=flip_filter + ) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + return x + + # Fast path: 1x1 convolution with upsampling only => convolve first, then upsample. + if kw == 1 and kh == 1 and (up > 1 and down == 1): + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + x = upfirdn2d( + x=x, + f=f, + up=up, + padding=[px0, px1, py0, py1], + gain=up**2, + flip_filter=flip_filter, + ) + return x + + # Fast path: downsampling only => use strided convolution. + if down > 1 and up == 1: + x = upfirdn2d(x=x, f=f, padding=[px0, px1, py0, py1], flip_filter=flip_filter) + x = _conv2d_wrapper( + x=x, w=w, stride=down, groups=groups, flip_weight=flip_weight + ) + return x + + # Fast path: upsampling with optional downsampling => use transpose strided convolution. + if up > 1: + if groups == 1: + w = w.transpose(0, 1) + else: + w = w.reshape(groups, out_channels // groups, in_channels_per_group, kh, kw) + w = w.transpose(1, 2) + w = w.reshape( + groups * in_channels_per_group, out_channels // groups, kh, kw + ) + px0 -= kw - 1 + px1 -= kw - up + py0 -= kh - 1 + py1 -= kh - up + pxt = max(min(-px0, -px1), 0) + pyt = max(min(-py0, -py1), 0) + x = _conv2d_wrapper( + x=x, + w=w, + stride=up, + padding=[pyt, pxt], + groups=groups, + transpose=True, + flip_weight=(not flip_weight), + ) + x = upfirdn2d( + x=x, + f=f, + padding=[px0 + pxt, px1 + pxt, py0 + pyt, py1 + pyt], + gain=up**2, + flip_filter=flip_filter, + ) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + # Fast path: no up/downsampling, padding supported by the underlying implementation => use plain conv2d. + if up == 1 and down == 1: + if px0 == px1 and py0 == py1 and px0 >= 0 and py0 >= 0: + return _conv2d_wrapper( + x=x, w=w, padding=[py0, px0], groups=groups, flip_weight=flip_weight + ) + + # Fallback: Generic reference implementation. + x = upfirdn2d( + x=x, + f=(f if up > 1 else None), + up=up, + padding=[px0, px1, py0, py1], + gain=up**2, + flip_filter=flip_filter, + ) + x = _conv2d_wrapper(x=x, w=w, groups=groups, flip_weight=flip_weight) + if down > 1: + x = upfirdn2d(x=x, f=f, down=down, flip_filter=flip_filter) + return x + + +class Conv2dLayer(torch.nn.Module): + def __init__( + self, + in_channels, # Number of input channels. + out_channels, # Number of output channels. + kernel_size, # Width and height of the convolution kernel. + bias=True, # Apply additive bias before the activation function? + activation="linear", # Activation function: 'relu', 'lrelu', etc. + up=1, # Integer upsampling factor. + down=1, # Integer downsampling factor. + resample_filter=[ + 1, + 3, + 3, + 1, + ], # Low-pass filter to apply when resampling activations. + conv_clamp=None, # Clamp the output to +-X, None = disable clamping. + channels_last=False, # Expect the input to have memory_format=channels_last? + trainable=True, # Update the weights of this layer during training? + ): + super().__init__() + self.activation = activation + self.up = up + self.down = down + self.register_buffer("resample_filter", setup_filter(resample_filter)) + self.conv_clamp = conv_clamp + self.padding = kernel_size // 2 + self.weight_gain = 1 / np.sqrt(in_channels * (kernel_size**2)) + self.act_gain = activation_funcs[activation].def_gain + + memory_format = ( + torch.channels_last if channels_last else torch.contiguous_format + ) + weight = torch.randn([out_channels, in_channels, kernel_size, kernel_size]).to( + memory_format=memory_format + ) + bias = torch.zeros([out_channels]) if bias else None + if trainable: + self.weight = torch.nn.Parameter(weight) + self.bias = torch.nn.Parameter(bias) if bias is not None else None + else: + self.register_buffer("weight", weight) + if bias is not None: + self.register_buffer("bias", bias) + else: + self.bias = None + + def forward(self, x, gain=1): + w = self.weight * self.weight_gain + x = conv2d_resample( + x=x, + w=w, + f=self.resample_filter, + up=self.up, + down=self.down, + padding=self.padding, + ) + + act_gain = self.act_gain * gain + act_clamp = self.conv_clamp * gain if self.conv_clamp is not None else None + out = bias_act( + x, self.bias, act=self.activation, gain=act_gain, clamp=act_clamp + ) + return out + + +def torch_gc(): + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.ipc_collect() + gc.collect() + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +def get_scheduler(sd_sampler, scheduler_config): + # https://github.com/huggingface/diffusers/issues/4167 + keys_to_pop = ["use_karras_sigmas", "algorithm_type"] + scheduler_config = dict(scheduler_config) + for it in keys_to_pop: + scheduler_config.pop(it, None) + + # fmt: off + samplers = { + SDSampler.dpm_plus_plus_2m: [DPMSolverMultistepScheduler], + SDSampler.dpm_plus_plus_2m_karras: [DPMSolverMultistepScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm_plus_plus_2m_sde: [DPMSolverMultistepScheduler, dict(algorithm_type="sde-dpmsolver++")], + SDSampler.dpm_plus_plus_2m_sde_karras: [DPMSolverMultistepScheduler, dict(algorithm_type="sde-dpmsolver++", use_karras_sigmas=True)], + SDSampler.dpm_plus_plus_sde: [DPMSolverSinglestepScheduler], + SDSampler.dpm_plus_plus_sde_karras: [DPMSolverSinglestepScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm2: [KDPM2DiscreteScheduler], + SDSampler.dpm2_karras: [KDPM2DiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.dpm2_a: [KDPM2AncestralDiscreteScheduler], + SDSampler.dpm2_a_karras: [KDPM2AncestralDiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.euler: [EulerDiscreteScheduler], + SDSampler.euler_a: [EulerAncestralDiscreteScheduler], + SDSampler.heun: [HeunDiscreteScheduler], + SDSampler.lms: [LMSDiscreteScheduler], + SDSampler.lms_karras: [LMSDiscreteScheduler, dict(use_karras_sigmas=True)], + SDSampler.ddim: [DDIMScheduler], + SDSampler.pndm: [PNDMScheduler], + SDSampler.uni_pc: [UniPCMultistepScheduler], + SDSampler.lcm: [LCMScheduler], + } + # fmt: on + if sd_sampler in samplers: + if len(samplers[sd_sampler]) == 2: + scheduler_cls, kwargs = samplers[sd_sampler] + else: + scheduler_cls, kwargs = samplers[sd_sampler][0], {} + return scheduler_cls.from_config(scheduler_config, **kwargs) + else: + raise ValueError(sd_sampler) + + +def is_local_files_only(**kwargs) -> bool: + from huggingface_hub.constants import HF_HUB_OFFLINE + + return HF_HUB_OFFLINE or kwargs.get("local_files_only", False) + + +def handle_from_pretrained_exceptions(func, **kwargs): + try: + return func(**kwargs) + except ValueError as e: + if "You are trying to load the model files of the `variant=fp16`" in str(e): + logger.info("variant=fp16 not found, try revision=fp16") + try: + return func(**{**kwargs, "variant": None, "revision": "fp16"}) + except Exception as e: + logger.info("revision=fp16 not found, try revision=main") + return func(**{**kwargs, "variant": None, "revision": "main"}) + raise e + except OSError as e: + previous_traceback = traceback.format_exc() + if "RevisionNotFoundError: 404 Client Error." in previous_traceback: + logger.info("revision=fp16 not found, try revision=main") + return func(**{**kwargs, "variant": None, "revision": "main"}) + elif "Max retries exceeded" in previous_traceback: + logger.exception( + "Fetching model from HuggingFace failed. " + "If this is your first time downloading the model, you may need to set up proxy in terminal." + "If the model has already been downloaded, you can add --local-files-only when starting." + ) + exit(-1) + raise e + except Exception as e: + raise e + + +def get_torch_dtype(device, no_half: bool): + device = str(device) + use_fp16 = not no_half + use_gpu = device == "cuda" + # https://github.com/huggingface/diffusers/issues/4480 + # pipe.enable_attention_slicing and float16 will cause black output on mps + # if device in ["cuda", "mps"] and use_fp16: + if device in ["cuda"] and use_fp16: + return use_gpu, torch.float16 + return use_gpu, torch.float32 + + +def enable_low_mem(pipe, enable: bool): + if torch.backends.mps.is_available(): + # https://huggingface.co/docs/diffusers/v0.25.0/en/api/pipelines/stable_diffusion/image_variation#diffusers.StableDiffusionImageVariationPipeline.enable_attention_slicing + # CUDA: Don't enable attention slicing if you're already using `scaled_dot_product_attention` (SDPA) from PyTorch 2.0 or xFormers. + if enable: + pipe.enable_attention_slicing("max") + else: + # https://huggingface.co/docs/diffusers/optimization/mps + # Devices with less than 64GB of memory are recommended to use enable_attention_slicing + pipe.enable_attention_slicing() + + if enable: + pipe.vae.enable_tiling() diff --git a/py/iopaint/model/zits.py b/py/iopaint/model/zits.py new file mode 100644 index 0000000..d58ac01 --- /dev/null +++ b/py/iopaint/model/zits.py @@ -0,0 +1,476 @@ +import os +import time + +import cv2 +import torch +import torch.nn.functional as F + +from iopaint.helper import get_cache_path_by_url, load_jit_model, download_model +from iopaint.schema import InpaintRequest +import numpy as np + +from .base import InpaintModel + +ZITS_INPAINT_MODEL_URL = os.environ.get( + "ZITS_INPAINT_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-inpaint-0717.pt", +) +ZITS_INPAINT_MODEL_MD5 = os.environ.get( + "ZITS_INPAINT_MODEL_MD5", "9978cc7157dc29699e42308d675b2154" +) + +ZITS_EDGE_LINE_MODEL_URL = os.environ.get( + "ZITS_EDGE_LINE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-edge-line-0717.pt", +) +ZITS_EDGE_LINE_MODEL_MD5 = os.environ.get( + "ZITS_EDGE_LINE_MODEL_MD5", "55e31af21ba96bbf0c80603c76ea8c5f" +) + +ZITS_STRUCTURE_UPSAMPLE_MODEL_URL = os.environ.get( + "ZITS_STRUCTURE_UPSAMPLE_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-structure-upsample-0717.pt", +) +ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 = os.environ.get( + "ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5", "3d88a07211bd41b2ec8cc0d999f29927" +) + +ZITS_WIRE_FRAME_MODEL_URL = os.environ.get( + "ZITS_WIRE_FRAME_MODEL_URL", + "https://github.com/Sanster/models/releases/download/add_zits/zits-wireframe-0717.pt", +) +ZITS_WIRE_FRAME_MODEL_MD5 = os.environ.get( + "ZITS_WIRE_FRAME_MODEL_MD5", "a9727c63a8b48b65c905d351b21ce46b" +) + + +def resize(img, height, width, center_crop=False): + imgh, imgw = img.shape[0:2] + + if center_crop and imgh != imgw: + # center crop + side = np.minimum(imgh, imgw) + j = (imgh - side) // 2 + i = (imgw - side) // 2 + img = img[j : j + side, i : i + side, ...] + + if imgh > height and imgw > width: + inter = cv2.INTER_AREA + else: + inter = cv2.INTER_LINEAR + img = cv2.resize(img, (height, width), interpolation=inter) + + return img + + +def to_tensor(img, scale=True, norm=False): + if img.ndim == 2: + img = img[:, :, np.newaxis] + c = img.shape[-1] + + if scale: + img_t = torch.from_numpy(img).permute(2, 0, 1).float().div(255) + else: + img_t = torch.from_numpy(img).permute(2, 0, 1).float() + + if norm: + mean = torch.tensor([0.5, 0.5, 0.5]).reshape(c, 1, 1) + std = torch.tensor([0.5, 0.5, 0.5]).reshape(c, 1, 1) + img_t = (img_t - mean) / std + return img_t + + +def load_masked_position_encoding(mask): + ones_filter = np.ones((3, 3), dtype=np.float32) + d_filter1 = np.array([[1, 1, 0], [1, 1, 0], [0, 0, 0]], dtype=np.float32) + d_filter2 = np.array([[0, 0, 0], [1, 1, 0], [1, 1, 0]], dtype=np.float32) + d_filter3 = np.array([[0, 1, 1], [0, 1, 1], [0, 0, 0]], dtype=np.float32) + d_filter4 = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], dtype=np.float32) + str_size = 256 + pos_num = 128 + + ori_mask = mask.copy() + ori_h, ori_w = ori_mask.shape[0:2] + ori_mask = ori_mask / 255 + mask = cv2.resize(mask, (str_size, str_size), interpolation=cv2.INTER_AREA) + mask[mask > 0] = 255 + h, w = mask.shape[0:2] + mask3 = mask.copy() + mask3 = 1.0 - (mask3 / 255.0) + pos = np.zeros((h, w), dtype=np.int32) + direct = np.zeros((h, w, 4), dtype=np.int32) + i = 0 + while np.sum(1 - mask3) > 0: + i += 1 + mask3_ = cv2.filter2D(mask3, -1, ones_filter) + mask3_[mask3_ > 0] = 1 + sub_mask = mask3_ - mask3 + pos[sub_mask == 1] = i + + m = cv2.filter2D(mask3, -1, d_filter1) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 0] = 1 + + m = cv2.filter2D(mask3, -1, d_filter2) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 1] = 1 + + m = cv2.filter2D(mask3, -1, d_filter3) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 2] = 1 + + m = cv2.filter2D(mask3, -1, d_filter4) + m[m > 0] = 1 + m = m - mask3 + direct[m == 1, 3] = 1 + + mask3 = mask3_ + + abs_pos = pos.copy() + rel_pos = pos / (str_size / 2) # to 0~1 maybe larger than 1 + rel_pos = (rel_pos * pos_num).astype(np.int32) + rel_pos = np.clip(rel_pos, 0, pos_num - 1) + + if ori_w != w or ori_h != h: + rel_pos = cv2.resize(rel_pos, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) + rel_pos[ori_mask == 0] = 0 + direct = cv2.resize(direct, (ori_w, ori_h), interpolation=cv2.INTER_NEAREST) + direct[ori_mask == 0, :] = 0 + + return rel_pos, abs_pos, direct + + +def load_image(img, mask, device, sigma256=3.0): + """ + Args: + img: [H, W, C] RGB + mask: [H, W] 255 为 masks 区域 + sigma256: + + Returns: + + """ + h, w, _ = img.shape + imgh, imgw = img.shape[0:2] + img_256 = resize(img, 256, 256) + + mask = (mask > 127).astype(np.uint8) * 255 + mask_256 = cv2.resize(mask, (256, 256), interpolation=cv2.INTER_AREA) + mask_256[mask_256 > 0] = 255 + + mask_512 = cv2.resize(mask, (512, 512), interpolation=cv2.INTER_AREA) + mask_512[mask_512 > 0] = 255 + + # original skimage implemention + # https://scikit-image.org/docs/stable/api/skimage.feature.html#skimage.feature.canny + # low_threshold: Lower bound for hysteresis thresholding (linking edges). If None, low_threshold is set to 10% of dtype’s max. + # high_threshold: Upper bound for hysteresis thresholding (linking edges). If None, high_threshold is set to 20% of dtype’s max. + + try: + import skimage + + gray_256 = skimage.color.rgb2gray(img_256) + edge_256 = skimage.feature.canny(gray_256, sigma=3.0, mask=None).astype(float) + # cv2.imwrite("skimage_gray.jpg", (gray_256*255).astype(np.uint8)) + # cv2.imwrite("skimage_edge.jpg", (edge_256*255).astype(np.uint8)) + except: + gray_256 = cv2.cvtColor(img_256, cv2.COLOR_RGB2GRAY) + gray_256_blured = cv2.GaussianBlur( + gray_256, ksize=(7, 7), sigmaX=sigma256, sigmaY=sigma256 + ) + edge_256 = cv2.Canny( + gray_256_blured, threshold1=int(255 * 0.1), threshold2=int(255 * 0.2) + ) + + # cv2.imwrite("opencv_edge.jpg", edge_256) + + # line + img_512 = resize(img, 512, 512) + + rel_pos, abs_pos, direct = load_masked_position_encoding(mask) + + batch = dict() + batch["images"] = to_tensor(img.copy()).unsqueeze(0).to(device) + batch["img_256"] = to_tensor(img_256, norm=True).unsqueeze(0).to(device) + batch["masks"] = to_tensor(mask).unsqueeze(0).to(device) + batch["mask_256"] = to_tensor(mask_256).unsqueeze(0).to(device) + batch["mask_512"] = to_tensor(mask_512).unsqueeze(0).to(device) + batch["edge_256"] = to_tensor(edge_256, scale=False).unsqueeze(0).to(device) + batch["img_512"] = to_tensor(img_512).unsqueeze(0).to(device) + batch["rel_pos"] = torch.LongTensor(rel_pos).unsqueeze(0).to(device) + batch["abs_pos"] = torch.LongTensor(abs_pos).unsqueeze(0).to(device) + batch["direct"] = torch.LongTensor(direct).unsqueeze(0).to(device) + batch["h"] = imgh + batch["w"] = imgw + + return batch + + +def to_device(data, device): + if isinstance(data, torch.Tensor): + return data.to(device) + if isinstance(data, dict): + for key in data: + if isinstance(data[key], torch.Tensor): + data[key] = data[key].to(device) + return data + if isinstance(data, list): + return [to_device(d, device) for d in data] + + +class ZITS(InpaintModel): + name = "zits" + min_size = 256 + pad_mod = 32 + pad_to_square = True + is_erase_model = True + + def __init__(self, device, **kwargs): + """ + + Args: + device: + """ + super().__init__(device) + self.device = device + self.sample_edge_line_iterations = 1 + + def init_model(self, device, **kwargs): + self.wireframe = load_jit_model( + ZITS_WIRE_FRAME_MODEL_URL, device, ZITS_WIRE_FRAME_MODEL_MD5 + ) + self.edge_line = load_jit_model( + ZITS_EDGE_LINE_MODEL_URL, device, ZITS_EDGE_LINE_MODEL_MD5 + ) + self.structure_upsample = load_jit_model( + ZITS_STRUCTURE_UPSAMPLE_MODEL_URL, device, ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 + ) + self.inpaint = load_jit_model( + ZITS_INPAINT_MODEL_URL, device, ZITS_INPAINT_MODEL_MD5 + ) + + @staticmethod + def download(): + download_model(ZITS_WIRE_FRAME_MODEL_URL, ZITS_WIRE_FRAME_MODEL_MD5) + download_model(ZITS_EDGE_LINE_MODEL_URL, ZITS_EDGE_LINE_MODEL_MD5) + download_model( + ZITS_STRUCTURE_UPSAMPLE_MODEL_URL, ZITS_STRUCTURE_UPSAMPLE_MODEL_MD5 + ) + download_model(ZITS_INPAINT_MODEL_URL, ZITS_INPAINT_MODEL_MD5) + + @staticmethod + def is_downloaded() -> bool: + model_paths = [ + get_cache_path_by_url(ZITS_WIRE_FRAME_MODEL_URL), + get_cache_path_by_url(ZITS_EDGE_LINE_MODEL_URL), + get_cache_path_by_url(ZITS_STRUCTURE_UPSAMPLE_MODEL_URL), + get_cache_path_by_url(ZITS_INPAINT_MODEL_URL), + ] + return all([os.path.exists(it) for it in model_paths]) + + def wireframe_edge_and_line(self, items, enable: bool): + # 最终向 items 中添加 edge 和 line key + if not enable: + items["edge"] = torch.zeros_like(items["masks"]) + items["line"] = torch.zeros_like(items["masks"]) + return + + start = time.time() + try: + line_256 = self.wireframe_forward( + items["img_512"], + h=256, + w=256, + masks=items["mask_512"], + mask_th=0.85, + ) + except: + line_256 = torch.zeros_like(items["mask_256"]) + + print(f"wireframe_forward time: {(time.time() - start) * 1000:.2f}ms") + + # np_line = (line[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line.jpg", np_line) + + start = time.time() + edge_pred, line_pred = self.sample_edge_line_logits( + context=[items["img_256"], items["edge_256"], line_256], + mask=items["mask_256"].clone(), + iterations=self.sample_edge_line_iterations, + add_v=0.05, + mul_v=4, + ) + print(f"sample_edge_line_logits time: {(time.time() - start) * 1000:.2f}ms") + + # np_edge_pred = (edge_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("edge_pred.jpg", np_edge_pred) + # np_line_pred = (line_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line_pred.jpg", np_line_pred) + # exit() + + input_size = min(items["h"], items["w"]) + if input_size != 256 and input_size > 256: + while edge_pred.shape[2] < input_size: + edge_pred = self.structure_upsample(edge_pred) + edge_pred = torch.sigmoid((edge_pred + 2) * 2) + + line_pred = self.structure_upsample(line_pred) + line_pred = torch.sigmoid((line_pred + 2) * 2) + + edge_pred = F.interpolate( + edge_pred, + size=(input_size, input_size), + mode="bilinear", + align_corners=False, + ) + line_pred = F.interpolate( + line_pred, + size=(input_size, input_size), + mode="bilinear", + align_corners=False, + ) + + # np_edge_pred = (edge_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("edge_pred_upsample.jpg", np_edge_pred) + # np_line_pred = (line_pred[0][0].numpy() * 255).astype(np.uint8) + # cv2.imwrite("line_pred_upsample.jpg", np_line_pred) + # exit() + + items["edge"] = edge_pred.detach() + items["line"] = line_pred.detach() + + @torch.no_grad() + def forward(self, image, mask, config: InpaintRequest): + """Input images and output images have same size + images: [H, W, C] RGB + masks: [H, W] + return: BGR IMAGE + """ + mask = mask[:, :, 0] + items = load_image(image, mask, device=self.device) + + self.wireframe_edge_and_line(items, config.zits_wireframe) + + inpainted_image = self.inpaint( + items["images"], + items["masks"], + items["edge"], + items["line"], + items["rel_pos"], + items["direct"], + ) + + inpainted_image = inpainted_image * 255.0 + inpainted_image = ( + inpainted_image.cpu().permute(0, 2, 3, 1)[0].numpy().astype(np.uint8) + ) + inpainted_image = inpainted_image[:, :, ::-1] + + # cv2.imwrite("inpainted.jpg", inpainted_image) + # exit() + + return inpainted_image + + def wireframe_forward(self, images, h, w, masks, mask_th=0.925): + lcnn_mean = torch.tensor([109.730, 103.832, 98.681]).reshape(1, 3, 1, 1) + lcnn_std = torch.tensor([22.275, 22.124, 23.229]).reshape(1, 3, 1, 1) + images = images * 255.0 + # the masks value of lcnn is 127.5 + masked_images = images * (1 - masks) + torch.ones_like(images) * masks * 127.5 + masked_images = (masked_images - lcnn_mean) / lcnn_std + + def to_int(x): + return tuple(map(int, x)) + + lines_tensor = [] + lmap = np.zeros((h, w)) + + output_masked = self.wireframe(masked_images) + + output_masked = to_device(output_masked, "cpu") + if output_masked["num_proposals"] == 0: + lines_masked = [] + scores_masked = [] + else: + lines_masked = output_masked["lines_pred"].numpy() + lines_masked = [ + [line[1] * h, line[0] * w, line[3] * h, line[2] * w] + for line in lines_masked + ] + scores_masked = output_masked["lines_score"].numpy() + + for line, score in zip(lines_masked, scores_masked): + if score > mask_th: + try: + import skimage + + rr, cc, value = skimage.draw.line_aa( + *to_int(line[0:2]), *to_int(line[2:4]) + ) + lmap[rr, cc] = np.maximum(lmap[rr, cc], value) + except: + cv2.line( + lmap, + to_int(line[0:2][::-1]), + to_int(line[2:4][::-1]), + (1, 1, 1), + 1, + cv2.LINE_AA, + ) + + lmap = np.clip(lmap * 255, 0, 255).astype(np.uint8) + lines_tensor.append(to_tensor(lmap).unsqueeze(0)) + + lines_tensor = torch.cat(lines_tensor, dim=0) + return lines_tensor.detach().to(self.device) + + def sample_edge_line_logits( + self, context, mask=None, iterations=1, add_v=0, mul_v=4 + ): + [img, edge, line] = context + + img = img * (1 - mask) + edge = edge * (1 - mask) + line = line * (1 - mask) + + for i in range(iterations): + edge_logits, line_logits = self.edge_line(img, edge, line, masks=mask) + + edge_pred = torch.sigmoid(edge_logits) + line_pred = torch.sigmoid((line_logits + add_v) * mul_v) + edge = edge + edge_pred * mask + edge[edge >= 0.25] = 1 + edge[edge < 0.25] = 0 + line = line + line_pred * mask + + b, _, h, w = edge_pred.shape + edge_pred = edge_pred.reshape(b, -1, 1) + line_pred = line_pred.reshape(b, -1, 1) + mask = mask.reshape(b, -1) + + edge_probs = torch.cat([1 - edge_pred, edge_pred], dim=-1) + line_probs = torch.cat([1 - line_pred, line_pred], dim=-1) + edge_probs[:, :, 1] += 0.5 + line_probs[:, :, 1] += 0.5 + edge_max_probs = edge_probs.max(dim=-1)[0] + (1 - mask) * (-100) + line_max_probs = line_probs.max(dim=-1)[0] + (1 - mask) * (-100) + + indices = torch.sort( + edge_max_probs + line_max_probs, dim=-1, descending=True + )[1] + + for ii in range(b): + keep = int((i + 1) / iterations * torch.sum(mask[ii, ...])) + + assert torch.sum(mask[ii][indices[ii, :keep]]) == keep, "Error!!!" + mask[ii][indices[ii, :keep]] = 0 + + mask = mask.reshape(b, 1, h, w) + edge = edge * (1 - mask) + line = line * (1 - mask) + + edge, line = edge.to(torch.float32), line.to(torch.float32) + return edge, line diff --git a/py/iopaint/model_info.py b/py/iopaint/model_info.py new file mode 100644 index 0000000..5929543 --- /dev/null +++ b/py/iopaint/model_info.py @@ -0,0 +1,103 @@ +from typing import List + +from pydantic import computed_field, BaseModel + +from .const import ( + SDXL_CONTROLNET_CHOICES, + SD2_CONTROLNET_CHOICES, + SD_CONTROLNET_CHOICES, + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, +) +from .schema import ModelType + + +class ModelInfo(BaseModel): + name: str + path: str + model_type: ModelType + is_single_file_diffusers: bool = False + + @computed_field + @property + def need_prompt(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [ + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + ] + + @computed_field + @property + def controlnets(self) -> List[str]: + if self.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return SDXL_CONTROLNET_CHOICES + if self.model_type in [ModelType.DIFFUSERS_SD, ModelType.DIFFUSERS_SD_INPAINT]: + if "sd2" in self.name.lower(): + return SD2_CONTROLNET_CHOICES + else: + return SD_CONTROLNET_CHOICES + if self.name == POWERPAINT_NAME: + return SD_CONTROLNET_CHOICES + return [] + + @computed_field + @property + def support_strength(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [POWERPAINT_NAME, ANYTEXT_NAME] + + @computed_field + @property + def support_outpainting(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [KANDINSKY22_NAME, POWERPAINT_NAME] + + @computed_field + @property + def support_lcm_lora(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_controlnet(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_freeu(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [INSTRUCT_PIX2PIX_NAME] diff --git a/py/iopaint/model_manager.py b/py/iopaint/model_manager.py new file mode 100644 index 0000000..374aabb --- /dev/null +++ b/py/iopaint/model_manager.py @@ -0,0 +1,196 @@ +from typing import List, Dict + +import torch +from loguru import logger +import numpy as np + +from .download import scan_models +from .helper import switch_mps_device +from .model import models, ControlNet, SD, SDXL +from .model.utils import torch_gc, is_local_files_only +from .schema import InpaintRequest, ModelInfo, ModelType + + +class ModelManager: + def __init__(self, name: str, device: torch.device, **kwargs): + self.name = name + self.device = device + self.kwargs = kwargs + self.available_models: Dict[str, ModelInfo] = {} + self.scan_models() + + self.enable_controlnet = kwargs.get("enable_controlnet", False) + controlnet_method = kwargs.get("controlnet_method", None) + if ( + controlnet_method is None + and name in self.available_models + and self.available_models[name].support_controlnet + ): + controlnet_method = self.available_models[name].controlnets[0] + self.controlnet_method = controlnet_method + self.model = self.init_model(name, device, **kwargs) + + @property + def current_model(self) -> ModelInfo: + return self.available_models[self.name] + + def init_model(self, name: str, device, **kwargs): + logger.info(f"Loading model: {name}") + if name not in self.available_models: + raise NotImplementedError( + f"Unsupported model: {name}. Available models: {list(self.available_models.keys())}" + ) + + model_info = self.available_models[name] + kwargs = { + **kwargs, + "model_info": model_info, + "enable_controlnet": self.enable_controlnet, + "controlnet_method": self.controlnet_method, + } + + if model_info.support_controlnet and self.enable_controlnet: + return ControlNet(device, **kwargs) + elif model_info.name in models: + return models[name](device, **kwargs) + else: + if model_info.model_type in [ + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SD, + ]: + return SD(device, **kwargs) + + if model_info.model_type in [ + ModelType.DIFFUSERS_SDXL_INPAINT, + ModelType.DIFFUSERS_SDXL, + ]: + return SDXL(device, **kwargs) + + raise NotImplementedError(f"Unsupported model: {name}") + + @torch.inference_mode() + def __call__(self, image, mask, config: InpaintRequest): + """ + + Args: + image: [H, W, C] RGB + mask: [H, W, 1] 255 means area to repaint + config: + + Returns: + BGR image + """ + self.switch_controlnet_method(config) + self.enable_disable_freeu(config) + self.enable_disable_lcm_lora(config) + return self.model(image, mask, config).astype(np.uint8) + + def scan_models(self) -> List[ModelInfo]: + available_models = scan_models() + self.available_models = {it.name: it for it in available_models} + return available_models + + def switch(self, new_name: str): + if new_name == self.name: + return + + old_name = self.name + old_controlnet_method = self.controlnet_method + self.name = new_name + + if ( + self.available_models[new_name].support_controlnet + and self.controlnet_method + not in self.available_models[new_name].controlnets + ): + self.controlnet_method = self.available_models[new_name].controlnets[0] + try: + # TODO: enable/disable controlnet without reload model + del self.model + torch_gc() + + self.model = self.init_model( + new_name, switch_mps_device(new_name, self.device), **self.kwargs + ) + except Exception as e: + self.name = old_name + self.controlnet_method = old_controlnet_method + logger.info(f"Switch model from {old_name} to {new_name} failed, rollback") + self.model = self.init_model( + old_name, switch_mps_device(old_name, self.device), **self.kwargs + ) + raise e + + def switch_controlnet_method(self, config): + if not self.available_models[self.name].support_controlnet: + return + + if ( + self.enable_controlnet + and config.controlnet_method + and self.controlnet_method != config.controlnet_method + ): + old_controlnet_method = self.controlnet_method + self.controlnet_method = config.controlnet_method + self.model.switch_controlnet_method(config.controlnet_method) + logger.info( + f"Switch Controlnet method from {old_controlnet_method} to {config.controlnet_method}" + ) + elif self.enable_controlnet != config.enable_controlnet: + self.enable_controlnet = config.enable_controlnet + self.controlnet_method = config.controlnet_method + + pipe_components = { + "vae": self.model.model.vae, + "text_encoder": self.model.model.text_encoder, + "unet": self.model.model.unet, + } + if hasattr(self.model.model, "text_encoder_2"): + pipe_components["text_encoder_2"] = self.model.model.text_encoder_2 + + self.model = self.init_model( + self.name, + switch_mps_device(self.name, self.device), + pipe_components=pipe_components, + **self.kwargs, + ) + if not config.enable_controlnet: + logger.info(f"Disable controlnet") + else: + logger.info(f"Enable controlnet: {config.controlnet_method}") + + def enable_disable_freeu(self, config: InpaintRequest): + if str(self.model.device) == "mps": + return + + if self.available_models[self.name].support_freeu: + if config.sd_freeu: + freeu_config = config.sd_freeu_config + self.model.model.enable_freeu( + s1=freeu_config.s1, + s2=freeu_config.s2, + b1=freeu_config.b1, + b2=freeu_config.b2, + ) + else: + self.model.model.disable_freeu() + + def enable_disable_lcm_lora(self, config: InpaintRequest): + if self.available_models[self.name].support_lcm_lora: + # TODO: change this if load other lora is supported + lcm_lora_loaded = bool(self.model.model.get_list_adapters()) + if config.sd_lcm_lora: + if not lcm_lora_loaded: + logger.info("Load LCM LORA") + self.model.model.load_lora_weights( + self.model.lcm_lora_id, + weight_name="pytorch_lora_weights.safetensors", + local_files_only=is_local_files_only(), + ) + else: + logger.info("Enable LCM LORA") + self.model.model.enable_lora() + else: + if lcm_lora_loaded: + logger.info("Disable LCM LORA") + self.model.model.disable_lora() diff --git a/py/iopaint/plugins/__init__.py b/py/iopaint/plugins/__init__.py new file mode 100644 index 0000000..8128025 --- /dev/null +++ b/py/iopaint/plugins/__init__.py @@ -0,0 +1,74 @@ +from typing import Dict + +from loguru import logger + +from .anime_seg import AnimeSeg +from .gfpgan_plugin import GFPGANPlugin +from .interactive_seg import InteractiveSeg +from .realesrgan import RealESRGANUpscaler +from .remove_bg import RemoveBG +from .restoreformer import RestoreFormerPlugin +from ..schema import InteractiveSegModel, Device, RealESRGANModel + + +def build_plugins( + enable_interactive_seg: bool, + interactive_seg_model: InteractiveSegModel, + interactive_seg_device: Device, + enable_remove_bg: bool, + remove_bg_model: str, + enable_anime_seg: bool, + enable_realesrgan: bool, + realesrgan_device: Device, + realesrgan_model: RealESRGANModel, + enable_gfpgan: bool, + gfpgan_device: Device, + enable_restoreformer: bool, + restoreformer_device: Device, + no_half: bool, +) -> Dict: + plugins = {} + if enable_interactive_seg: + logger.info(f"Initialize {InteractiveSeg.name} plugin") + plugins[InteractiveSeg.name] = InteractiveSeg( + interactive_seg_model, interactive_seg_device + ) + + if enable_remove_bg: + logger.info(f"Initialize {RemoveBG.name} plugin") + plugins[RemoveBG.name] = RemoveBG(remove_bg_model) + + if enable_anime_seg: + logger.info(f"Initialize {AnimeSeg.name} plugin") + plugins[AnimeSeg.name] = AnimeSeg() + + if enable_realesrgan: + logger.info( + f"Initialize {RealESRGANUpscaler.name} plugin: {realesrgan_model}, {realesrgan_device}" + ) + plugins[RealESRGANUpscaler.name] = RealESRGANUpscaler( + realesrgan_model, + realesrgan_device, + no_half=no_half, + ) + + if enable_gfpgan: + logger.info(f"Initialize {GFPGANPlugin.name} plugin") + if enable_realesrgan: + logger.info("Use realesrgan as GFPGAN background upscaler") + else: + logger.info( + f"GFPGAN no background upscaler, use --enable-realesrgan to enable it" + ) + plugins[GFPGANPlugin.name] = GFPGANPlugin( + gfpgan_device, + upscaler=plugins.get(RealESRGANUpscaler.name, None), + ) + + if enable_restoreformer: + logger.info(f"Initialize {RestoreFormerPlugin.name} plugin") + plugins[RestoreFormerPlugin.name] = RestoreFormerPlugin( + restoreformer_device, + upscaler=plugins.get(RealESRGANUpscaler.name, None), + ) + return plugins diff --git a/py/iopaint/plugins/anime_seg.py b/py/iopaint/plugins/anime_seg.py new file mode 100644 index 0000000..286564b --- /dev/null +++ b/py/iopaint/plugins/anime_seg.py @@ -0,0 +1,462 @@ +import cv2 +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np +from PIL import Image + +from iopaint.helper import load_model +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.schema import RunPluginRequest + + +class REBNCONV(nn.Module): + def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1): + super(REBNCONV, self).__init__() + + self.conv_s1 = nn.Conv2d( + in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride + ) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self, x): + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src, tar): + src = F.interpolate(src, size=tar.shape[2:], mode="bilinear", align_corners=False) + + return src + + +### RSU-7 ### +class RSU7(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7, self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1)) + hx6dup = _upsample_like(hx6d, hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-5 ### +class RSU5(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4 ### +class RSU4(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4F ### +class RSU4F(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2) + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1)) + hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1)) + + return hx1d + hxin + + +class ISNetDIS(nn.Module): + def __init__(self, in_ch=3, out_ch=1): + super(ISNetDIS, self).__init__() + + self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1) + self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage1 = RSU7(64, 32, 64) + self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage2 = RSU6(64, 32, 128) + self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage3 = RSU5(128, 64, 256) + self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage4 = RSU4(256, 128, 512) + self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage5 = RSU4F(512, 256, 512) + self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage6 = RSU4F(512, 256, 512) + + # decoder + self.stage5d = RSU4F(1024, 256, 512) + self.stage4d = RSU4(1024, 128, 256) + self.stage3d = RSU5(512, 64, 128) + self.stage2d = RSU6(256, 32, 64) + self.stage1d = RSU7(128, 16, 64) + + self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + return d1.sigmoid() + + +# 从小到大 +ANIME_SEG_MODELS = { + "url": "https://github.com/Sanster/models/releases/download/isnetis/isnetis.pth", + "md5": "5f25479076b73074730ab8de9e8f2051", +} + + +class AnimeSeg(BasePlugin): + # Model from: https://github.com/SkyTNT/anime-segmentation + name = "AnimeSeg" + support_gen_image = True + support_gen_mask = True + + def __init__(self): + super().__init__() + self.model = load_model( + ISNetDIS(), + ANIME_SEG_MODELS["url"], + "cpu", + ANIME_SEG_MODELS["md5"], + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + mask = self.forward(rgb_np_img) + mask = Image.fromarray(mask, mode="L") + h0, w0 = rgb_np_img.shape[0], rgb_np_img.shape[1] + empty = Image.new("RGBA", (w0, h0), 0) + img = Image.fromarray(rgb_np_img) + cutout = Image.composite(img, empty, mask) + return np.asarray(cutout) + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + return self.forward(rgb_np_img) + + @torch.inference_mode() + def forward(self, rgb_np_img): + s = 1024 + + h0, w0 = h, w = rgb_np_img.shape[0], rgb_np_img.shape[1] + if h > w: + h, w = s, int(s * w / h) + else: + h, w = int(s * h / w), s + ph, pw = s - h, s - w + tmpImg = np.zeros([s, s, 3], dtype=np.float32) + tmpImg[ph // 2 : ph // 2 + h, pw // 2 : pw // 2 + w] = ( + cv2.resize(rgb_np_img, (w, h)) / 255 + ) + tmpImg = tmpImg.transpose((2, 0, 1)) + tmpImg = torch.from_numpy(tmpImg).unsqueeze(0).type(torch.FloatTensor) + mask = self.model(tmpImg) + mask = mask[0, :, ph // 2 : ph // 2 + h, pw // 2 : pw // 2 + w] + mask = cv2.resize(mask.cpu().numpy().transpose((1, 2, 0)), (w0, h0)) + return (mask * 255).astype("uint8") diff --git a/py/iopaint/plugins/base_plugin.py b/py/iopaint/plugins/base_plugin.py new file mode 100644 index 0000000..1f8bddc --- /dev/null +++ b/py/iopaint/plugins/base_plugin.py @@ -0,0 +1,30 @@ +from loguru import logger +import numpy as np + +from iopaint.schema import RunPluginRequest + + +class BasePlugin: + name: str + support_gen_image: bool = False + support_gen_mask: bool = False + + def __init__(self): + err_msg = self.check_dep() + if err_msg: + logger.error(err_msg) + exit(-1) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + # return RGBA np image or BGR np image + ... + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + # return GRAY or BGR np image, 255 means foreground, 0 means background + ... + + def check_dep(self): + ... + + def switch_model(self, new_model_name: str): + ... diff --git a/py/iopaint/plugins/briarmbg.py b/py/iopaint/plugins/briarmbg.py new file mode 100644 index 0000000..880f530 --- /dev/null +++ b/py/iopaint/plugins/briarmbg.py @@ -0,0 +1,512 @@ +# copy from: https://huggingface.co/spaces/briaai/BRIA-RMBG-1.4/blob/main/briarmbg.py +import cv2 +import torch +import torch.nn as nn +import torch.nn.functional as F +from PIL import Image +import numpy as np +from torchvision.transforms.functional import normalize + + +class REBNCONV(nn.Module): + def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1): + super(REBNCONV, self).__init__() + + self.conv_s1 = nn.Conv2d( + in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride + ) + self.bn_s1 = nn.BatchNorm2d(out_ch) + self.relu_s1 = nn.ReLU(inplace=True) + + def forward(self, x): + hx = x + xout = self.relu_s1(self.bn_s1(self.conv_s1(hx))) + + return xout + + +## upsample tensor 'src' to have the same spatial size with tensor 'tar' +def _upsample_like(src, tar): + src = F.interpolate(src, size=tar.shape[2:], mode="bilinear") + + return src + + +### RSU-7 ### +class RSU7(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512): + super(RSU7, self).__init__() + + self.in_ch = in_ch + self.mid_ch = mid_ch + self.out_ch = out_ch + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) ## 1 -> 1/2 + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + b, c, h, w = x.shape + + hx = x + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + hx = self.pool5(hx5) + + hx6 = self.rebnconv6(hx) + + hx7 = self.rebnconv7(hx6) + + hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1)) + hx6dup = _upsample_like(hx6d, hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-6 ### +class RSU6(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU6, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + hx = self.pool4(hx4) + + hx5 = self.rebnconv5(hx) + + hx6 = self.rebnconv6(hx5) + + hx5d = self.rebnconv5d(torch.cat((hx6, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-5 ### +class RSU5(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU5, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + hx = self.pool3(hx3) + + hx4 = self.rebnconv4(hx) + + hx5 = self.rebnconv5(hx4) + + hx4d = self.rebnconv4d(torch.cat((hx5, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4 ### +class RSU4(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1) + self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=2) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx = self.pool1(hx1) + + hx2 = self.rebnconv2(hx) + hx = self.pool2(hx2) + + hx3 = self.rebnconv3(hx) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1)) + + return hx1d + hxin + + +### RSU-4F ### +class RSU4F(nn.Module): + def __init__(self, in_ch=3, mid_ch=12, out_ch=3): + super(RSU4F, self).__init__() + + self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1) + + self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1) + self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=2) + self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=4) + + self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=8) + + self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=4) + self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=2) + self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1) + + def forward(self, x): + hx = x + + hxin = self.rebnconvin(hx) + + hx1 = self.rebnconv1(hxin) + hx2 = self.rebnconv2(hx1) + hx3 = self.rebnconv3(hx2) + + hx4 = self.rebnconv4(hx3) + + hx3d = self.rebnconv3d(torch.cat((hx4, hx3), 1)) + hx2d = self.rebnconv2d(torch.cat((hx3d, hx2), 1)) + hx1d = self.rebnconv1d(torch.cat((hx2d, hx1), 1)) + + return hx1d + hxin + + +class myrebnconv(nn.Module): + def __init__( + self, + in_ch=3, + out_ch=1, + kernel_size=3, + stride=1, + padding=1, + dilation=1, + groups=1, + ): + super(myrebnconv, self).__init__() + + self.conv = nn.Conv2d( + in_ch, + out_ch, + kernel_size=kernel_size, + stride=stride, + padding=padding, + dilation=dilation, + groups=groups, + ) + self.bn = nn.BatchNorm2d(out_ch) + self.rl = nn.ReLU(inplace=True) + + def forward(self, x): + return self.rl(self.bn(self.conv(x))) + + +class BriaRMBG(nn.Module): + def __init__(self, in_ch=3, out_ch=1): + super(BriaRMBG, self).__init__() + + self.conv_in = nn.Conv2d(in_ch, 64, 3, stride=2, padding=1) + self.pool_in = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage1 = RSU7(64, 32, 64) + self.pool12 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage2 = RSU6(64, 32, 128) + self.pool23 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage3 = RSU5(128, 64, 256) + self.pool34 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage4 = RSU4(256, 128, 512) + self.pool45 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage5 = RSU4F(512, 256, 512) + self.pool56 = nn.MaxPool2d(2, stride=2, ceil_mode=True) + + self.stage6 = RSU4F(512, 256, 512) + + # decoder + self.stage5d = RSU4F(1024, 256, 512) + self.stage4d = RSU4(1024, 128, 256) + self.stage3d = RSU5(512, 64, 128) + self.stage2d = RSU6(256, 32, 64) + self.stage1d = RSU7(128, 16, 64) + + self.side1 = nn.Conv2d(64, out_ch, 3, padding=1) + self.side2 = nn.Conv2d(64, out_ch, 3, padding=1) + self.side3 = nn.Conv2d(128, out_ch, 3, padding=1) + self.side4 = nn.Conv2d(256, out_ch, 3, padding=1) + self.side5 = nn.Conv2d(512, out_ch, 3, padding=1) + self.side6 = nn.Conv2d(512, out_ch, 3, padding=1) + + # self.outconv = nn.Conv2d(6*out_ch,out_ch,1) + + def forward(self, x): + hx = x + + hxin = self.conv_in(hx) + # hx = self.pool_in(hxin) + + # stage 1 + hx1 = self.stage1(hxin) + hx = self.pool12(hx1) + + # stage 2 + hx2 = self.stage2(hx) + hx = self.pool23(hx2) + + # stage 3 + hx3 = self.stage3(hx) + hx = self.pool34(hx3) + + # stage 4 + hx4 = self.stage4(hx) + hx = self.pool45(hx4) + + # stage 5 + hx5 = self.stage5(hx) + hx = self.pool56(hx5) + + # stage 6 + hx6 = self.stage6(hx) + hx6up = _upsample_like(hx6, hx5) + + # -------------------- decoder -------------------- + hx5d = self.stage5d(torch.cat((hx6up, hx5), 1)) + hx5dup = _upsample_like(hx5d, hx4) + + hx4d = self.stage4d(torch.cat((hx5dup, hx4), 1)) + hx4dup = _upsample_like(hx4d, hx3) + + hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1)) + hx3dup = _upsample_like(hx3d, hx2) + + hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1)) + hx2dup = _upsample_like(hx2d, hx1) + + hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1)) + + # side output + d1 = self.side1(hx1d) + d1 = _upsample_like(d1, x) + + d2 = self.side2(hx2d) + d2 = _upsample_like(d2, x) + + d3 = self.side3(hx3d) + d3 = _upsample_like(d3, x) + + d4 = self.side4(hx4d) + d4 = _upsample_like(d4, x) + + d5 = self.side5(hx5d) + d5 = _upsample_like(d5, x) + + d6 = self.side6(hx6) + d6 = _upsample_like(d6, x) + + return [ + F.sigmoid(d1), + F.sigmoid(d2), + F.sigmoid(d3), + F.sigmoid(d4), + F.sigmoid(d5), + F.sigmoid(d6), + ], [hx1d, hx2d, hx3d, hx4d, hx5d, hx6] + + +def resize_image(image): + image = image.convert("RGB") + model_input_size = (1024, 1024) + image = image.resize(model_input_size, Image.BILINEAR) + return image + + +def create_briarmbg_session(): + from huggingface_hub import hf_hub_download + + net = BriaRMBG() + model_path = hf_hub_download("briaai/RMBG-1.4", "model.pth") + net.load_state_dict(torch.load(model_path, map_location="cpu")) + net.eval() + return net + + +def briarmbg_process(bgr_np_image, session, only_mask=False): + # prepare input + orig_bgr_image = Image.fromarray(bgr_np_image) + w, h = orig_im_size = orig_bgr_image.size + image = resize_image(orig_bgr_image) + im_np = np.array(image) + im_tensor = torch.tensor(im_np, dtype=torch.float32).permute(2, 0, 1) + im_tensor = torch.unsqueeze(im_tensor, 0) + im_tensor = torch.divide(im_tensor, 255.0) + im_tensor = normalize(im_tensor, [0.5, 0.5, 0.5], [1.0, 1.0, 1.0]) + # inference + result = session(im_tensor) + # post process + result = torch.squeeze(F.interpolate(result[0][0], size=(h, w), mode="bilinear"), 0) + ma = torch.max(result) + mi = torch.min(result) + result = (result - mi) / (ma - mi) + # image to pil + im_array = (result * 255).cpu().data.numpy().astype(np.uint8) + + mask = np.squeeze(im_array) + if only_mask: + return mask + + pil_im = Image.fromarray(mask) + # paste the mask on the original image + new_im = Image.new("RGBA", pil_im.size, (0, 0, 0, 0)) + new_im.paste(orig_bgr_image, mask=pil_im) + rgba_np_img = np.asarray(new_im) + return rgba_np_img diff --git a/py/iopaint/plugins/gfpgan_plugin.py b/py/iopaint/plugins/gfpgan_plugin.py new file mode 100644 index 0000000..619280b --- /dev/null +++ b/py/iopaint/plugins/gfpgan_plugin.py @@ -0,0 +1,74 @@ +import cv2 +import numpy as np +from loguru import logger + +from iopaint.helper import download_model +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.schema import RunPluginRequest + + +class GFPGANPlugin(BasePlugin): + name = "GFPGAN" + support_gen_image = True + + def __init__(self, device, upscaler=None): + super().__init__() + from .gfpganer import MyGFPGANer + + url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth" + model_md5 = "94d735072630ab734561130a47bc44f8" + model_path = download_model(url, model_md5) + logger.info(f"GFPGAN model path: {model_path}") + + import facexlib + + if hasattr(facexlib.detection.retinaface, "device"): + facexlib.detection.retinaface.device = device + + # Use GFPGAN for face enhancement + self.face_enhancer = MyGFPGANer( + model_path=model_path, + upscale=1, + arch="clean", + channel_multiplier=2, + device=device, + bg_upsampler=upscaler.model if upscaler is not None else None, + ) + self.face_enhancer.face_helper.face_det.mean_tensor.to(device) + self.face_enhancer.face_helper.face_det = ( + self.face_enhancer.face_helper.face_det.to(device) + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + weight = 0.5 + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"GFPGAN input shape: {bgr_np_img.shape}") + _, _, bgr_output = self.face_enhancer.enhance( + bgr_np_img, + has_aligned=False, + only_center_face=False, + paste_back=True, + weight=weight, + ) + logger.info(f"GFPGAN output shape: {bgr_output.shape}") + + # try: + # if scale != 2: + # interpolation = cv2.INTER_AREA if scale < 2 else cv2.INTER_LANCZOS4 + # h, w = img.shape[0:2] + # output = cv2.resize( + # output, + # (int(w * scale / 2), int(h * scale / 2)), + # interpolation=interpolation, + # ) + # except Exception as error: + # print("wrong scale input.", error) + return bgr_output + + def check_dep(self): + try: + import gfpgan + except ImportError: + return ( + "gfpgan is not installed, please install it first. pip install gfpgan" + ) diff --git a/py/iopaint/plugins/gfpganer.py b/py/iopaint/plugins/gfpganer.py new file mode 100644 index 0000000..75a575d --- /dev/null +++ b/py/iopaint/plugins/gfpganer.py @@ -0,0 +1,84 @@ +import os + +import torch +from facexlib.utils.face_restoration_helper import FaceRestoreHelper +from gfpgan import GFPGANv1Clean, GFPGANer +from torch.hub import get_dir + + +class MyGFPGANer(GFPGANer): + """Helper for restoration with GFPGAN. + + It will detect and crop faces, and then resize the faces to 512x512. + GFPGAN is used to restored the resized faces. + The background is upsampled with the bg_upsampler. + Finally, the faces will be pasted back to the upsample background image. + + Args: + model_path (str): The path to the GFPGAN model. It can be urls (will first download it automatically). + upscale (float): The upscale of the final output. Default: 2. + arch (str): The GFPGAN architecture. Option: clean | original. Default: clean. + channel_multiplier (int): Channel multiplier for large networks of StyleGAN2. Default: 2. + bg_upsampler (nn.Module): The upsampler for the background. Default: None. + """ + + def __init__( + self, + model_path, + upscale=2, + arch="clean", + channel_multiplier=2, + bg_upsampler=None, + device=None, + ): + self.upscale = upscale + self.bg_upsampler = bg_upsampler + + # initialize model + self.device = ( + torch.device("cuda" if torch.cuda.is_available() else "cpu") + if device is None + else device + ) + # initialize the GFP-GAN + if arch == "clean": + self.gfpgan = GFPGANv1Clean( + out_size=512, + num_style_feat=512, + channel_multiplier=channel_multiplier, + decoder_load_path=None, + fix_decoder=False, + num_mlp=8, + input_is_latent=True, + different_w=True, + narrow=1, + sft_half=True, + ) + elif arch == "RestoreFormer": + from gfpgan.archs.restoreformer_arch import RestoreFormer + + self.gfpgan = RestoreFormer() + + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + + # initialize face helper + self.face_helper = FaceRestoreHelper( + upscale, + face_size=512, + crop_ratio=(1, 1), + det_model="retinaface_resnet50", + save_ext="png", + use_parse=True, + device=self.device, + model_rootpath=model_dir, + ) + + loadnet = torch.load(model_path) + if "params_ema" in loadnet: + keyname = "params_ema" + else: + keyname = "params" + self.gfpgan.load_state_dict(loadnet[keyname], strict=True) + self.gfpgan.eval() + self.gfpgan = self.gfpgan.to(self.device) diff --git a/py/iopaint/plugins/interactive_seg.py b/py/iopaint/plugins/interactive_seg.py new file mode 100644 index 0000000..a270991 --- /dev/null +++ b/py/iopaint/plugins/interactive_seg.py @@ -0,0 +1,107 @@ +import hashlib +from typing import List + +import numpy as np +import torch +from loguru import logger + +from iopaint.helper import download_model +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.plugins.segment_anything import SamPredictor, sam_model_registry +from iopaint.plugins.segment_anything.predictor_hq import SamHQPredictor +from iopaint.schema import RunPluginRequest + +# 从小到大 +SEGMENT_ANYTHING_MODELS = { + "vit_b": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth", + "md5": "01ec64d29a2fca3f0661936605ae66f8", + }, + "vit_l": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth", + "md5": "0b3195507c641ddb6910d2bb5adee89c", + }, + "vit_h": { + "url": "https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth", + "md5": "4b8939a88964f0f4ff5f5b2642c598a6", + }, + "mobile_sam": { + "url": "https://github.com/Sanster/models/releases/download/MobileSAM/mobile_sam.pt", + "md5": "f3c0d8cda613564d499310dab6c812cd", + }, + "sam_hq_vit_b": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_b.pth", + "md5": "c6b8953247bcfdc8bb8ef91e36a6cacc", + }, + "sam_hq_vit_l": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_l.pth", + "md5": "08947267966e4264fb39523eccc33f86", + }, + "sam_hq_vit_h": { + "url": "https://huggingface.co/lkeab/hq-sam/resolve/main/sam_hq_vit_h.pth", + "md5": "3560f6b6a5a6edacd814a1325c39640a", + }, +} + + +class InteractiveSeg(BasePlugin): + name = "InteractiveSeg" + support_gen_mask = True + + def __init__(self, model_name, device): + super().__init__() + self.model_name = model_name + self.device = device + self._init_session(model_name) + + def _init_session(self, model_name: str): + model_path = download_model( + SEGMENT_ANYTHING_MODELS[model_name]["url"], + SEGMENT_ANYTHING_MODELS[model_name]["md5"], + ) + logger.info(f"SegmentAnything model path: {model_path}") + if "sam_hq" in model_name: + self.predictor = SamHQPredictor( + sam_model_registry[model_name](checkpoint=model_path).to(self.device) + ) + else: + self.predictor = SamPredictor( + sam_model_registry[model_name](checkpoint=model_path).to(self.device) + ) + self.prev_img_md5 = None + + def switch_model(self, new_model_name): + if self.model_name == new_model_name: + return + + logger.info( + f"Switching InteractiveSeg model from {self.model_name} to {new_model_name}" + ) + self._init_session(new_model_name) + self.model_name = new_model_name + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + img_md5 = hashlib.md5(req.image.encode("utf-8")).hexdigest() + return self.forward(rgb_np_img, req.clicks, img_md5) + + @torch.inference_mode() + def forward(self, rgb_np_img, clicks: List[List], img_md5: str): + input_point = [] + input_label = [] + for click in clicks: + x = click[0] + y = click[1] + input_point.append([x, y]) + input_label.append(click[2]) + + if img_md5 and img_md5 != self.prev_img_md5: + self.prev_img_md5 = img_md5 + self.predictor.set_image(rgb_np_img) + + masks, scores, _ = self.predictor.predict( + point_coords=np.array(input_point), + point_labels=np.array(input_label), + multimask_output=False, + ) + mask = masks[0].astype(np.uint8) * 255 + return mask diff --git a/py/iopaint/plugins/realesrgan.py b/py/iopaint/plugins/realesrgan.py new file mode 100644 index 0000000..5275700 --- /dev/null +++ b/py/iopaint/plugins/realesrgan.py @@ -0,0 +1,109 @@ +import cv2 +import numpy as np +import torch +from loguru import logger + +from iopaint.helper import download_model +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.schema import RunPluginRequest, RealESRGANModel + + +class RealESRGANUpscaler(BasePlugin): + name = "RealESRGAN" + support_gen_image = True + + def __init__(self, name, device, no_half=False): + super().__init__() + self.model_name = name + self.device = device + self.no_half = no_half + self._init_model(name) + + def _init_model(self, name): + from basicsr.archs.rrdbnet_arch import RRDBNet + from realesrgan import RealESRGANer + from realesrgan.archs.srvgg_arch import SRVGGNetCompact + + REAL_ESRGAN_MODELS = { + RealESRGANModel.realesr_general_x4v3: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + "scale": 4, + "model": lambda: SRVGGNetCompact( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_conv=32, + upscale=4, + act_type="prelu", + ), + "model_md5": "91a7644643c884ee00737db24e478156", + }, + RealESRGANModel.RealESRGAN_x4plus: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth", + "scale": 4, + "model": lambda: RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=23, + num_grow_ch=32, + scale=4, + ), + "model_md5": "99ec365d4afad750833258a1a24f44ca", + }, + RealESRGANModel.RealESRGAN_x4plus_anime_6B: { + "url": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth", + "scale": 4, + "model": lambda: RRDBNet( + num_in_ch=3, + num_out_ch=3, + num_feat=64, + num_block=6, + num_grow_ch=32, + scale=4, + ), + "model_md5": "d58ce384064ec1591c2ea7b79dbf47ba", + }, + } + if name not in REAL_ESRGAN_MODELS: + raise ValueError(f"Unknown RealESRGAN model name: {name}") + model_info = REAL_ESRGAN_MODELS[name] + + model_path = download_model(model_info["url"], model_info["model_md5"]) + logger.info(f"RealESRGAN model path: {model_path}") + + self.model = RealESRGANer( + scale=model_info["scale"], + model_path=model_path, + model=model_info["model"](), + half=True if "cuda" in str(self.device) and not self.no_half else False, + tile=512, + tile_pad=10, + pre_pad=10, + device=self.device, + ) + + def switch_model(self, new_model_name: str): + if self.model_name == new_model_name: + return + self._init_model(new_model_name) + self.model_name = new_model_name + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"RealESRGAN input shape: {bgr_np_img.shape}, scale: {req.scale}") + result = self.forward(bgr_np_img, req.scale) + logger.info(f"RealESRGAN output shape: {result.shape}") + return result + + @torch.inference_mode() + def forward(self, bgr_np_img, scale: float): + # 输出是 BGR + upsampled = self.model.enhance(bgr_np_img, outscale=scale)[0] + return upsampled + + def check_dep(self): + try: + import realesrgan + except ImportError: + return "RealESRGAN is not installed, please install it first. pip install realesrgan" diff --git a/py/iopaint/plugins/remove_bg.py b/py/iopaint/plugins/remove_bg.py new file mode 100644 index 0000000..64bf785 --- /dev/null +++ b/py/iopaint/plugins/remove_bg.py @@ -0,0 +1,71 @@ +import os +import cv2 +import numpy as np +from loguru import logger +from torch.hub import get_dir + +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.schema import RunPluginRequest, RemoveBGModel + + +class RemoveBG(BasePlugin): + name = "RemoveBG" + support_gen_mask = True + support_gen_image = True + + def __init__(self, model_name): + super().__init__() + self.model_name = model_name + + hub_dir = get_dir() + model_dir = os.path.join(hub_dir, "checkpoints") + os.environ["U2NET_HOME"] = model_dir + + self._init_session(model_name) + + def _init_session(self, model_name: str): + if model_name == RemoveBGModel.briaai_rmbg_1_4: + from iopaint.plugins.briarmbg import ( + create_briarmbg_session, + briarmbg_process, + ) + + self.session = create_briarmbg_session() + self.remove = briarmbg_process + else: + from rembg import new_session, remove + + self.session = new_session(model_name=model_name) + self.remove = remove + + def switch_model(self, new_model_name): + if self.model_name == new_model_name: + return + + logger.info( + f"Switching removebg model from {self.model_name} to {new_model_name}" + ) + self._init_session(new_model_name) + self.model_name = new_model_name + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + + # return BGRA image + output = self.remove(bgr_np_img, session=self.session) + return cv2.cvtColor(output, cv2.COLOR_BGRA2RGBA) + + def gen_mask(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + + # return BGR image, 255 means foreground, 0 means background + output = self.remove(bgr_np_img, session=self.session, only_mask=True) + return output + + def check_dep(self): + try: + import rembg + except ImportError: + return ( + "RemoveBG is not installed, please install it first. pip install rembg" + ) diff --git a/py/iopaint/plugins/restoreformer.py b/py/iopaint/plugins/restoreformer.py new file mode 100644 index 0000000..4e1d3e7 --- /dev/null +++ b/py/iopaint/plugins/restoreformer.py @@ -0,0 +1,57 @@ +import cv2 +import numpy as np +from loguru import logger + +from iopaint.helper import download_model +from iopaint.plugins.base_plugin import BasePlugin +from iopaint.schema import RunPluginRequest + + +class RestoreFormerPlugin(BasePlugin): + name = "RestoreFormer" + support_gen_image = True + + def __init__(self, device, upscaler=None): + super().__init__() + from .gfpganer import MyGFPGANer + + url = "https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth" + model_md5 = "eaeeff6c4a1caa1673977cb374e6f699" + model_path = download_model(url, model_md5) + logger.info(f"RestoreFormer model path: {model_path}") + + import facexlib + + if hasattr(facexlib.detection.retinaface, "device"): + facexlib.detection.retinaface.device = device + + self.face_enhancer = MyGFPGANer( + model_path=model_path, + upscale=1, + arch="RestoreFormer", + channel_multiplier=2, + device=device, + bg_upsampler=upscaler.model if upscaler is not None else None, + ) + + def gen_image(self, rgb_np_img, req: RunPluginRequest) -> np.ndarray: + weight = 0.5 + bgr_np_img = cv2.cvtColor(rgb_np_img, cv2.COLOR_RGB2BGR) + logger.info(f"RestoreFormer input shape: {bgr_np_img.shape}") + _, _, bgr_output = self.face_enhancer.enhance( + bgr_np_img, + has_aligned=False, + only_center_face=False, + paste_back=True, + weight=weight, + ) + logger.info(f"RestoreFormer output shape: {bgr_output.shape}") + return bgr_output + + def check_dep(self): + try: + import gfpgan + except ImportError: + return ( + "gfpgan is not installed, please install it first. pip install gfpgan" + ) diff --git a/py/iopaint/plugins/segment_anything/__init__.py b/py/iopaint/plugins/segment_anything/__init__.py new file mode 100644 index 0000000..420f04b --- /dev/null +++ b/py/iopaint/plugins/segment_anything/__init__.py @@ -0,0 +1,16 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .build_sam import ( + build_sam_vit_h, + build_sam_vit_l, + build_sam_vit_b, + build_sam_vit_h_hq, + build_sam_vit_l_hq, + build_sam_vit_b_hq, + sam_model_registry, +) +from .predictor import SamPredictor diff --git a/py/iopaint/plugins/segment_anything/build_sam.py b/py/iopaint/plugins/segment_anything/build_sam.py new file mode 100644 index 0000000..9b905ef --- /dev/null +++ b/py/iopaint/plugins/segment_anything/build_sam.py @@ -0,0 +1,269 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from functools import partial + +from iopaint.plugins.segment_anything.modeling.tiny_vit_sam import TinyViT + +from .modeling import ( + ImageEncoderViT, + MaskDecoder, + PromptEncoder, + Sam, + TwoWayTransformer, +) +from .modeling.image_encoder_hq import ImageEncoderViTHQ +from .modeling.mask_decoder import MaskDecoderHQ +from .modeling.sam_hq import SamHQ + + +def build_sam_vit_h(checkpoint=None): + return _build_sam( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_vit_l(checkpoint=None): + return _build_sam( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b(checkpoint=None): + return _build_sam( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +def build_sam_vit_t(checkpoint=None): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + mobile_sam = Sam( + image_encoder=TinyViT( + img_size=1024, + in_chans=3, + num_classes=1000, + embed_dims=[64, 128, 160, 320], + depths=[2, 2, 6, 2], + num_heads=[2, 4, 5, 10], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4.0, + drop_rate=0.0, + drop_path_rate=0.0, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=0.8, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + + mobile_sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + mobile_sam.load_state_dict(state_dict) + return mobile_sam + + +def build_sam_vit_h_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1280, + encoder_depth=32, + encoder_num_heads=16, + encoder_global_attn_indexes=[7, 15, 23, 31], + checkpoint=checkpoint, + ) + + +def build_sam_vit_l_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=1024, + encoder_depth=24, + encoder_num_heads=16, + encoder_global_attn_indexes=[5, 11, 17, 23], + checkpoint=checkpoint, + ) + + +def build_sam_vit_b_hq(checkpoint=None): + return _build_sam_hq( + encoder_embed_dim=768, + encoder_depth=12, + encoder_num_heads=12, + encoder_global_attn_indexes=[2, 5, 8, 11], + checkpoint=checkpoint, + ) + + +sam_model_registry = { + "default": build_sam_vit_h, + "vit_h": build_sam_vit_h, + "vit_l": build_sam_vit_l, + "vit_b": build_sam_vit_b, + "sam_hq_vit_h": build_sam_vit_h_hq, + "sam_hq_vit_l": build_sam_vit_l_hq, + "sam_hq_vit_b": build_sam_vit_b_hq, + "mobile_sam": build_sam_vit_t, +} + + +def _build_sam( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = Sam( + image_encoder=ImageEncoderViT( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + state_dict = torch.load(f) + sam.load_state_dict(state_dict) + return sam + + +def _build_sam_hq( + encoder_embed_dim, + encoder_depth, + encoder_num_heads, + encoder_global_attn_indexes, + checkpoint=None, +): + prompt_embed_dim = 256 + image_size = 1024 + vit_patch_size = 16 + image_embedding_size = image_size // vit_patch_size + sam = SamHQ( + image_encoder=ImageEncoderViTHQ( + depth=encoder_depth, + embed_dim=encoder_embed_dim, + img_size=image_size, + mlp_ratio=4, + norm_layer=partial(torch.nn.LayerNorm, eps=1e-6), + num_heads=encoder_num_heads, + patch_size=vit_patch_size, + qkv_bias=True, + use_rel_pos=True, + global_attn_indexes=encoder_global_attn_indexes, + window_size=14, + out_chans=prompt_embed_dim, + ), + prompt_encoder=PromptEncoder( + embed_dim=prompt_embed_dim, + image_embedding_size=(image_embedding_size, image_embedding_size), + input_image_size=(image_size, image_size), + mask_in_chans=16, + ), + mask_decoder=MaskDecoderHQ( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + vit_dim=encoder_embed_dim, + ), + pixel_mean=[123.675, 116.28, 103.53], + pixel_std=[58.395, 57.12, 57.375], + ) + sam.eval() + if checkpoint is not None: + with open(checkpoint, "rb") as f: + device = "cuda" if torch.cuda.is_available() else "cpu" + state_dict = torch.load(f, map_location=device) + info = sam.load_state_dict(state_dict, strict=False) + print(info) + for n, p in sam.named_parameters(): + if ( + "hf_token" not in n + and "hf_mlp" not in n + and "compress_vit_feat" not in n + and "embedding_encoder" not in n + and "embedding_maskfeature" not in n + ): + p.requires_grad = False + + return sam diff --git a/py/iopaint/plugins/segment_anything/modeling/__init__.py b/py/iopaint/plugins/segment_anything/modeling/__init__.py new file mode 100644 index 0000000..38e9062 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .sam import Sam +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder +from .transformer import TwoWayTransformer diff --git a/py/iopaint/plugins/segment_anything/modeling/common.py b/py/iopaint/plugins/segment_anything/modeling/common.py new file mode 100644 index 0000000..2bf1523 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/common.py @@ -0,0 +1,43 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn + +from typing import Type + + +class MLPBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + mlp_dim: int, + act: Type[nn.Module] = nn.GELU, + ) -> None: + super().__init__() + self.lin1 = nn.Linear(embedding_dim, mlp_dim) + self.lin2 = nn.Linear(mlp_dim, embedding_dim) + self.act = act() + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.lin2(self.act(self.lin1(x))) + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/image_encoder.py b/py/iopaint/plugins/segment_anything/modeling/image_encoder.py new file mode 100644 index 0000000..a6ad9ad --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/image_encoder.py @@ -0,0 +1,395 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViT(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + for blk in self.blocks: + x = blk(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (int or None): Input resolution for calculating the relative positional + parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool: If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (int or None): Input resolution for calculating the relative positional + parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W)) + + attn = attn.softmax(dim=-1) + x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1) + x = self.proj(x) + + return x + + +def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int] +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py b/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py new file mode 100644 index 0000000..f12803b --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/image_encoder_hq.py @@ -0,0 +1,422 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from typing import Optional, Tuple, Type + +from .common import LayerNorm2d, MLPBlock + + +# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa +class ImageEncoderViTHQ(nn.Module): + def __init__( + self, + img_size: int = 1024, + patch_size: int = 16, + in_chans: int = 3, + embed_dim: int = 768, + depth: int = 12, + num_heads: int = 12, + mlp_ratio: float = 4.0, + out_chans: int = 256, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_abs_pos: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + global_attn_indexes: Tuple[int, ...] = (), + ) -> None: + """ + Args: + img_size (int): Input image size. + patch_size (int): Patch size. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + depth (int): Depth of ViT. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_abs_pos (bool): If True, use absolute positional embeddings. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. + global_attn_indexes (list): Indexes for blocks using global attention. + """ + super().__init__() + self.img_size = img_size + + self.patch_embed = PatchEmbed( + kernel_size=(patch_size, patch_size), + stride=(patch_size, patch_size), + in_chans=in_chans, + embed_dim=embed_dim, + ) + + self.pos_embed: Optional[nn.Parameter] = None + if use_abs_pos: + # Initialize absolute positional embedding with pretrain image size. + self.pos_embed = nn.Parameter( + torch.zeros( + 1, img_size // patch_size, img_size // patch_size, embed_dim + ) + ) + + self.blocks = nn.ModuleList() + for i in range(depth): + block = Block( + dim=embed_dim, + num_heads=num_heads, + mlp_ratio=mlp_ratio, + qkv_bias=qkv_bias, + norm_layer=norm_layer, + act_layer=act_layer, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + window_size=window_size if i not in global_attn_indexes else 0, + input_size=(img_size // patch_size, img_size // patch_size), + ) + self.blocks.append(block) + + self.neck = nn.Sequential( + nn.Conv2d( + embed_dim, + out_chans, + kernel_size=1, + bias=False, + ), + LayerNorm2d(out_chans), + nn.Conv2d( + out_chans, + out_chans, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(out_chans), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.patch_embed(x) + if self.pos_embed is not None: + x = x + self.pos_embed + + interm_embeddings = [] + for blk in self.blocks: + x = blk(x) + if blk.window_size == 0: + interm_embeddings.append(x) + + x = self.neck(x.permute(0, 3, 1, 2)) + + return x, interm_embeddings + + +class Block(nn.Module): + """Transformer blocks with support of window attention and residual propagation blocks""" + + def __init__( + self, + dim: int, + num_heads: int, + mlp_ratio: float = 4.0, + qkv_bias: bool = True, + norm_layer: Type[nn.Module] = nn.LayerNorm, + act_layer: Type[nn.Module] = nn.GELU, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + window_size: int = 0, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads in each ViT block. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + norm_layer (nn.Module): Normalization layer. + act_layer (nn.Module): Activation layer. + use_rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + window_size (int): Window size for window attention blocks. If it equals 0, then + use global attention. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.norm1 = norm_layer(dim) + self.attn = Attention( + dim, + num_heads=num_heads, + qkv_bias=qkv_bias, + use_rel_pos=use_rel_pos, + rel_pos_zero_init=rel_pos_zero_init, + input_size=input_size if window_size == 0 else (window_size, window_size), + ) + + self.norm2 = norm_layer(dim) + self.mlp = MLPBlock( + embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer + ) + + self.window_size = window_size + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x + x = self.norm1(x) + # Window partition + if self.window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, self.window_size) + + x = self.attn(x) + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, self.window_size, pad_hw, (H, W)) + + x = shortcut + x + x = x + self.mlp(self.norm2(x)) + + return x + + +class Attention(nn.Module): + """Multi-head Attention block with relative position embeddings.""" + + def __init__( + self, + dim: int, + num_heads: int = 8, + qkv_bias: bool = True, + use_rel_pos: bool = False, + rel_pos_zero_init: bool = True, + input_size: Optional[Tuple[int, int]] = None, + ) -> None: + """ + Args: + dim (int): Number of input channels. + num_heads (int): Number of attention heads. + qkv_bias (bool): If True, add a learnable bias to query, key, value. + rel_pos (bool): If True, add relative positional embeddings to the attention map. + rel_pos_zero_init (bool): If True, zero initialize relative positional parameters. + input_size (tuple(int, int) or None): Input resolution for calculating the relative + positional parameter size. + """ + super().__init__() + self.num_heads = num_heads + head_dim = dim // num_heads + self.scale = head_dim**-0.5 + + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + self.use_rel_pos = use_rel_pos + if self.use_rel_pos: + assert ( + input_size is not None + ), "Input size must be provided if using relative positional encoding." + # initialize relative positional embeddings + self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim)) + self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (3, B, nHead, H * W, C) + qkv = ( + self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4) + ) + # q, k, v with shape (B * nHead, H * W, C) + q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0) + + attn = (q * self.scale) @ k.transpose(-2, -1) + + if self.use_rel_pos: + attn = add_decomposed_rel_pos( + attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W) + ) + + attn = attn.softmax(dim=-1) + x = ( + (attn @ v) + .view(B, self.num_heads, H, W, -1) + .permute(0, 2, 3, 1, 4) + .reshape(B, H, W, -1) + ) + x = self.proj(x) + + return x + + +def window_partition( + x: torch.Tensor, window_size: int +) -> Tuple[torch.Tensor, Tuple[int, int]]: + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition( + windows: torch.Tensor, + window_size: int, + pad_hw: Tuple[int, int], + hw: Tuple[int, int], +) -> torch.Tensor: + """ + Window unpartition into original sequences and removing padding. + Args: + windows (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor: + """ + Get relative positional embeddings according to the relative positions of + query and key sizes. + Args: + q_size (int): size of query q. + k_size (int): size of key k. + rel_pos (Tensor): relative position embeddings (L, C). + + Returns: + Extracted positional embeddings according to relative positions. + """ + max_rel_dist = int(2 * max(q_size, k_size) - 1) + # Interpolate rel pos if needed. + if rel_pos.shape[0] != max_rel_dist: + # Interpolate rel pos. + rel_pos_resized = F.interpolate( + rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1), + size=max_rel_dist, + mode="linear", + ) + rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0) + else: + rel_pos_resized = rel_pos + + # Scale the coords with short length if shapes for q and k are different. + q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0) + k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0) + relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0) + + return rel_pos_resized[relative_coords.long()] + + +def add_decomposed_rel_pos( + attn: torch.Tensor, + q: torch.Tensor, + rel_pos_h: torch.Tensor, + rel_pos_w: torch.Tensor, + q_size: Tuple[int, int], + k_size: Tuple[int, int], +) -> torch.Tensor: + """ + Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`. + https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950 + Args: + attn (Tensor): attention map. + q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C). + rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis. + rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis. + q_size (Tuple): spatial sequence size of query q with (q_h, q_w). + k_size (Tuple): spatial sequence size of key k with (k_h, k_w). + + Returns: + attn (Tensor): attention map with added relative positional embeddings. + """ + q_h, q_w = q_size + k_h, k_w = k_size + Rh = get_rel_pos(q_h, k_h, rel_pos_h) + Rw = get_rel_pos(q_w, k_w, rel_pos_w) + + B, _, dim = q.shape + r_q = q.reshape(B, q_h, q_w, dim) + rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) + rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) + + attn = ( + attn.view(B, q_h, q_w, k_h, k_w) + + rel_h[:, :, :, :, None] + + rel_w[:, :, :, None, :] + ).view(B, q_h * q_w, k_h * k_w) + + return attn + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, int] = (16, 16), + stride: Tuple[int, int] = (16, 16), + padding: Tuple[int, int] = (0, 0), + in_chans: int = 3, + embed_dim: int = 768, + ) -> None: + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): Patch embedding dimension. + """ + super().__init__() + + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py b/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py new file mode 100644 index 0000000..67e0f77 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/mask_decoder.py @@ -0,0 +1,410 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import List, Tuple, Type + +from .common import LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + tranformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + ) + + # Select the correct mask or masks for outptu + if multimask_output: + mask_slice = slice(1, None) + else: + mask_slice = slice(0, 1) + masks = masks[:, mask_slice, :, :] + iou_pred = iou_pred[:, mask_slice] + + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + upscaled_embedding = self.output_upscaling(src) + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + +# https://github.com/SysCV/sam-hq/blob/main/segment_anything/modeling/mask_decoder_hq.py#L17 +class MaskDecoderHQ(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + vit_dim: int = 1024, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth + ) + + # HQ-SAM parameters + self.hf_token = nn.Embedding(1, transformer_dim) # HQ-Ouptput-Token + self.hf_mlp = MLP( + transformer_dim, transformer_dim, transformer_dim // 8, 3 + ) # corresponding new MLP layer for HQ-Ouptput-Token + self.num_mask_tokens = self.num_mask_tokens + 1 + + # three conv fusion layers for obtaining HQ-Feature + self.compress_vit_feat = nn.Sequential( + nn.ConvTranspose2d(vit_dim, transformer_dim, kernel_size=2, stride=2), + LayerNorm2d(transformer_dim), + nn.GELU(), + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 8, kernel_size=2, stride=2 + ), + ) + + self.embedding_encoder = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + ) + self.embedding_maskfeature = nn.Sequential( + nn.Conv2d(transformer_dim // 8, transformer_dim // 4, 3, 1, 1), + LayerNorm2d(transformer_dim // 4), + nn.GELU(), + nn.Conv2d(transformer_dim // 4, transformer_dim // 8, 3, 1, 1), + ) + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + hq_token_only: bool, + interm_embeddings: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the ViT image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + """ + vit_features = interm_embeddings[0].permute( + 0, 3, 1, 2 + ) # early-layer ViT feature, after 1st global attention block in ViT + hq_features = self.embedding_encoder(image_embeddings) + self.compress_vit_feat( + vit_features + ) + + masks, iou_pred = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + hq_features=hq_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + # mask with highest score + mask_slice = slice(1, self.num_mask_tokens - 1) + iou_pred = iou_pred[:, mask_slice] + iou_pred, max_iou_idx = torch.max(iou_pred, dim=1) + iou_pred = iou_pred.unsqueeze(1) + masks_multi = masks[:, mask_slice, :, :] + masks_sam = masks_multi[ + torch.arange(masks_multi.size(0)), max_iou_idx + ].unsqueeze(1) + else: + # singale mask output, default + mask_slice = slice(0, 1) + iou_pred = iou_pred[:, mask_slice] + masks_sam = masks[:, mask_slice] + + masks_hq = masks[:, slice(self.num_mask_tokens - 1, self.num_mask_tokens)] + if hq_token_only: + masks = masks_hq + else: + masks = masks_sam + masks_hq + # Prepare output + return masks, iou_pred + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + hq_features: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight, self.hf_token.weight], + dim=0, + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + src = src + dense_prompt_embeddings + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + # Run the transformer + hs, src = self.transformer(src, pos_src, tokens) + iou_token_out = hs[:, 0, :] + mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = src.transpose(1, 2).view(b, c, h, w) + + upscaled_embedding_sam = self.output_upscaling(src) + upscaled_embedding_hq = self.embedding_maskfeature( + upscaled_embedding_sam + ) + hq_features.repeat(b, 1, 1, 1) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + if i < self.num_mask_tokens - 1: + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + else: + hyper_in_list.append(self.hf_mlp(mask_tokens_out[:, i, :])) + + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding_sam.shape + + masks_sam = ( + hyper_in[:, : self.num_mask_tokens - 1] + @ upscaled_embedding_sam.view(b, c, h * w) + ).view(b, -1, h, w) + masks_sam_hq = ( + hyper_in[:, self.num_mask_tokens - 1 :] + @ upscaled_embedding_hq.view(b, c, h * w) + ).view(b, -1, h, w) + masks = torch.cat([masks_sam, masks_sam_hq], dim=1) + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + + return masks, iou_pred + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py b/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py new file mode 100644 index 0000000..c3143f4 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch import nn + +from typing import Any, Optional, Tuple, Type + +from .common import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1]) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size) + point_embedding[labels == -1] = 0.0 + point_embedding[labels == -1] += self.not_a_point_embed.weight + point_embedding[labels == 0] += self.point_embeddings[0].weight + point_embedding[labels == 1] += self.point_embeddings[1].weight + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device()) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C diff --git a/py/iopaint/plugins/segment_anything/modeling/sam.py b/py/iopaint/plugins/segment_anything/modeling/sam.py new file mode 100644 index 0000000..303bc2f --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/sam.py @@ -0,0 +1,174 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class Sam(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + @torch.no_grad() + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input promts, + C is determiend by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings = self.image_encoder(input_images) + + outputs = [] + for image_record, curr_embedding in zip(batched_input, image_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/sam_hq.py b/py/iopaint/plugins/segment_anything/modeling/sam_hq.py new file mode 100644 index 0000000..d2ae3a3 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/sam_hq.py @@ -0,0 +1,177 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import nn +from torch.nn import functional as F + +from typing import Any, Dict, List, Tuple + +from .image_encoder import ImageEncoderViT +from .mask_decoder import MaskDecoder +from .prompt_encoder import PromptEncoder + + +class SamHQ(nn.Module): + mask_threshold: float = 0.0 + image_format: str = "RGB" + + def __init__( + self, + image_encoder: ImageEncoderViT, + prompt_encoder: PromptEncoder, + mask_decoder: MaskDecoder, + pixel_mean: List[float] = [123.675, 116.28, 103.53], + pixel_std: List[float] = [58.395, 57.12, 57.375], + ) -> None: + """ + SAM predicts object masks from an image and input prompts. + + Arguments: + image_encoder (ImageEncoderViT): The backbone used to encode the + image into image embeddings that allow for efficient mask prediction. + prompt_encoder (PromptEncoder): Encodes various types of input prompts. + mask_decoder (MaskDecoder): Predicts masks from the image embeddings + and encoded prompts. + pixel_mean (list(float)): Mean values for normalizing pixels in the input image. + pixel_std (list(float)): Std values for normalizing pixels in the input image. + """ + super().__init__() + self.image_encoder = image_encoder + self.prompt_encoder = prompt_encoder + self.mask_decoder = mask_decoder + self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False) + self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False) + + @property + def device(self) -> Any: + return self.pixel_mean.device + + def forward( + self, + batched_input: List[Dict[str, Any]], + multimask_output: bool, + hq_token_only: bool =False, + ) -> List[Dict[str, torch.Tensor]]: + """ + Predicts masks end-to-end from provided images and prompts. + If prompts are not known in advance, using SamPredictor is + recommended over calling the model directly. + + Arguments: + batched_input (list(dict)): A list over input images, each a + dictionary with the following keys. A prompt key can be + excluded if it is not present. + 'image': The image as a torch tensor in 3xHxW format, + already transformed for input to the model. + 'original_size': (tuple(int, int)) The original size of + the image before transformation, as (H, W). + 'point_coords': (torch.Tensor) Batched point prompts for + this image, with shape BxNx2. Already transformed to the + input frame of the model. + 'point_labels': (torch.Tensor) Batched labels for point prompts, + with shape BxN. + 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4. + Already transformed to the input frame of the model. + 'mask_inputs': (torch.Tensor) Batched mask inputs to the model, + in the form Bx1xHxW. + multimask_output (bool): Whether the model should predict multiple + disambiguating masks, or return a single mask. + + Returns: + (list(dict)): A list over input images, where each element is + as dictionary with the following keys. + 'masks': (torch.Tensor) Batched binary mask predictions, + with shape BxCxHxW, where B is the number of input prompts, + C is determined by multimask_output, and (H, W) is the + original size of the image. + 'iou_predictions': (torch.Tensor) The model's predictions + of mask quality, in shape BxC. + 'low_res_logits': (torch.Tensor) Low resolution logits with + shape BxCxHxW, where H=W=256. Can be passed as mask input + to subsequent iterations of prediction. + """ + input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0) + image_embeddings, interm_embeddings = self.image_encoder(input_images) + interm_embeddings = interm_embeddings[0] # early layer + + outputs = [] + for image_record, curr_embedding, curr_interm in zip(batched_input, image_embeddings, interm_embeddings): + if "point_coords" in image_record: + points = (image_record["point_coords"], image_record["point_labels"]) + else: + points = None + sparse_embeddings, dense_embeddings = self.prompt_encoder( + points=points, + boxes=image_record.get("boxes", None), + masks=image_record.get("mask_inputs", None), + ) + low_res_masks, iou_predictions = self.mask_decoder( + image_embeddings=curr_embedding.unsqueeze(0), + image_pe=self.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + hq_token_only=hq_token_only, + interm_embeddings=curr_interm.unsqueeze(0).unsqueeze(0), + ) + masks = self.postprocess_masks( + low_res_masks, + input_size=image_record["image"].shape[-2:], + original_size=image_record["original_size"], + ) + masks = masks > self.mask_threshold + outputs.append( + { + "masks": masks, + "iou_predictions": iou_predictions, + "low_res_logits": low_res_masks, + } + ) + return outputs + + def postprocess_masks( + self, + masks: torch.Tensor, + input_size: Tuple[int, ...], + original_size: Tuple[int, ...], + ) -> torch.Tensor: + """ + Remove padding and upscale masks to the original image size. + + Arguments: + masks (torch.Tensor): Batched masks from the mask_decoder, + in BxCxHxW format. + input_size (tuple(int, int)): The size of the image input to the + model, in (H, W) format. Used to remove padding. + original_size (tuple(int, int)): The original size of the image + before resizing for input to the model, in (H, W) format. + + Returns: + (torch.Tensor): Batched masks in BxCxHxW format, where (H, W) + is given by original_size. + """ + masks = F.interpolate( + masks, + (self.image_encoder.img_size, self.image_encoder.img_size), + mode="bilinear", + align_corners=False, + ) + masks = masks[..., : input_size[0], : input_size[1]] + masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False) + return masks + + def preprocess(self, x: torch.Tensor) -> torch.Tensor: + """Normalize pixel values and pad to a square input.""" + # Normalize colors + x = (x - self.pixel_mean) / self.pixel_std + + # Pad + h, w = x.shape[-2:] + padh = self.image_encoder.img_size - h + padw = self.image_encoder.img_size - w + x = F.pad(x, (0, padw, 0, padh)) + return x \ No newline at end of file diff --git a/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py b/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py new file mode 100644 index 0000000..a5127c7 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/tiny_vit_sam.py @@ -0,0 +1,822 @@ +# -------------------------------------------------------- +# TinyViT Model Architecture +# Copyright (c) 2022 Microsoft +# Adapted from LeViT and Swin Transformer +# LeViT: (https://github.com/facebookresearch/levit) +# Swin: (https://github.com/microsoft/swin-transformer) +# Build the TinyViT Model +# -------------------------------------------------------- + +import collections +import itertools +import math +import warnings +import torch +import torch.nn as nn +import torch.nn.functional as F +import torch.utils.checkpoint as checkpoint +from typing import Tuple + + +def _ntuple(n): + def parse(x): + if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): + return x + return tuple(itertools.repeat(x, n)) + + return parse + + +to_2tuple = _ntuple(2) + + +def _trunc_normal_(tensor, mean, std, a, b): + # Cut & paste from PyTorch official master until it's in a few official releases - RW + # Method based on https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf + def norm_cdf(x): + # Computes standard normal cumulative distribution function + return (1.0 + math.erf(x / math.sqrt(2.0))) / 2.0 + + if (mean < a - 2 * std) or (mean > b + 2 * std): + warnings.warn( + "mean is more than 2 std from [a, b] in nn.init.trunc_normal_. " + "The distribution of values may be incorrect.", + stacklevel=2, + ) + + # Values are generated by using a truncated uniform distribution and + # then using the inverse CDF for the normal distribution. + # Get upper and lower cdf values + l = norm_cdf((a - mean) / std) + u = norm_cdf((b - mean) / std) + + # Uniformly fill tensor with values from [l, u], then translate to + # [2l-1, 2u-1]. + tensor.uniform_(2 * l - 1, 2 * u - 1) + + # Use inverse cdf transform for normal distribution to get truncated + # standard normal + tensor.erfinv_() + + # Transform to proper mean, std + tensor.mul_(std * math.sqrt(2.0)) + tensor.add_(mean) + + # Clamp to ensure it's in the proper range + tensor.clamp_(min=a, max=b) + return tensor + + +def trunc_normal_(tensor, mean=0.0, std=1.0, a=-2.0, b=2.0): + # type: (Tensor, float, float, float, float) -> Tensor + r"""Fills the input Tensor with values drawn from a truncated + normal distribution. The values are effectively drawn from the + normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` + with values outside :math:`[a, b]` redrawn until they are within + the bounds. The method used for generating the random values works + best when :math:`a \leq \text{mean} \leq b`. + + NOTE: this impl is similar to the PyTorch trunc_normal_, the bounds [a, b] are + applied while sampling the normal with mean/std applied, therefore a, b args + should be adjusted to match the range of mean, std args. + + Args: + tensor: an n-dimensional `torch.Tensor` + mean: the mean of the normal distribution + std: the standard deviation of the normal distribution + a: the minimum cutoff value + b: the maximum cutoff value + Examples: + >>> w = torch.empty(3, 5) + >>> nn.init.trunc_normal_(w) + """ + with torch.no_grad(): + return _trunc_normal_(tensor, mean, std, a, b) + + +def drop_path( + x, drop_prob: float = 0.0, training: bool = False, scale_by_keep: bool = True +): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). + + This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, + the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... + See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for + changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use + 'survival rate' as the argument. + + """ + if drop_prob == 0.0 or not training: + return x + keep_prob = 1 - drop_prob + shape = (x.shape[0],) + (1,) * ( + x.ndim - 1 + ) # work with diff dim tensors, not just 2D ConvNets + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +class TimmDropPath(nn.Module): + """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).""" + + def __init__(self, drop_prob: float = 0.0, scale_by_keep: bool = True): + super(TimmDropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + return drop_path(x, self.drop_prob, self.training, self.scale_by_keep) + + def extra_repr(self): + return f"drop_prob={round(self.drop_prob,3):0.3f}" + + +class Conv2d_BN(torch.nn.Sequential): + def __init__( + self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1 + ): + super().__init__() + self.add_module( + "c", torch.nn.Conv2d(a, b, ks, stride, pad, dilation, groups, bias=False) + ) + bn = torch.nn.BatchNorm2d(b) + torch.nn.init.constant_(bn.weight, bn_weight_init) + torch.nn.init.constant_(bn.bias, 0) + self.add_module("bn", bn) + + @torch.no_grad() + def fuse(self): + c, bn = self._modules.values() + w = bn.weight / (bn.running_var + bn.eps) ** 0.5 + w = c.weight * w[:, None, None, None] + b = bn.bias - bn.running_mean * bn.weight / (bn.running_var + bn.eps) ** 0.5 + m = torch.nn.Conv2d( + w.size(1) * self.c.groups, + w.size(0), + w.shape[2:], + stride=self.c.stride, + padding=self.c.padding, + dilation=self.c.dilation, + groups=self.c.groups, + ) + m.weight.data.copy_(w) + m.bias.data.copy_(b) + return m + + +class DropPath(TimmDropPath): + def __init__(self, drop_prob=None): + super().__init__(drop_prob=drop_prob) + self.drop_prob = drop_prob + + def __repr__(self): + msg = super().__repr__() + msg += f"(drop_prob={self.drop_prob})" + return msg + + +class PatchEmbed(nn.Module): + def __init__(self, in_chans, embed_dim, resolution, activation): + super().__init__() + img_size: Tuple[int, int] = to_2tuple(resolution) + self.patches_resolution = (img_size[0] // 4, img_size[1] // 4) + self.num_patches = self.patches_resolution[0] * self.patches_resolution[1] + self.in_chans = in_chans + self.embed_dim = embed_dim + n = embed_dim + self.seq = nn.Sequential( + Conv2d_BN(in_chans, n // 2, 3, 2, 1), + activation(), + Conv2d_BN(n // 2, n, 3, 2, 1), + ) + + def forward(self, x): + return self.seq(x) + + +class MBConv(nn.Module): + def __init__(self, in_chans, out_chans, expand_ratio, activation, drop_path): + super().__init__() + self.in_chans = in_chans + self.hidden_chans = int(in_chans * expand_ratio) + self.out_chans = out_chans + + self.conv1 = Conv2d_BN(in_chans, self.hidden_chans, ks=1) + self.act1 = activation() + + self.conv2 = Conv2d_BN( + self.hidden_chans, + self.hidden_chans, + ks=3, + stride=1, + pad=1, + groups=self.hidden_chans, + ) + self.act2 = activation() + + self.conv3 = Conv2d_BN(self.hidden_chans, out_chans, ks=1, bn_weight_init=0.0) + self.act3 = activation() + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + shortcut = x + + x = self.conv1(x) + x = self.act1(x) + + x = self.conv2(x) + x = self.act2(x) + + x = self.conv3(x) + + x = self.drop_path(x) + + x += shortcut + x = self.act3(x) + + return x + + +class PatchMerging(nn.Module): + def __init__(self, input_resolution, dim, out_dim, activation): + super().__init__() + + self.input_resolution = input_resolution + self.dim = dim + self.out_dim = out_dim + self.act = activation() + self.conv1 = Conv2d_BN(dim, out_dim, 1, 1, 0) + stride_c = 2 + if out_dim == 320 or out_dim == 448 or out_dim == 576: + stride_c = 1 + self.conv2 = Conv2d_BN(out_dim, out_dim, 3, stride_c, 1, groups=out_dim) + self.conv3 = Conv2d_BN(out_dim, out_dim, 1, 1, 0) + + def forward(self, x): + if x.ndim == 3: + H, W = self.input_resolution + B = len(x) + # (B, C, H, W) + x = x.view(B, H, W, -1).permute(0, 3, 1, 2) + + x = self.conv1(x) + x = self.act(x) + + x = self.conv2(x) + x = self.act(x) + x = self.conv3(x) + x = x.flatten(2).transpose(1, 2) + return x + + +class ConvLayer(nn.Module): + def __init__( + self, + dim, + input_resolution, + depth, + activation, + drop_path=0.0, + downsample=None, + use_checkpoint=False, + out_dim=None, + conv_expand_ratio=4.0, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList( + [ + MBConv( + dim, + dim, + conv_expand_ratio, + activation, + drop_path[i] if isinstance(drop_path, list) else drop_path, + ) + for i in range(depth) + ] + ) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation + ) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + act_layer=nn.GELU, + drop=0.0, + ): + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + self.norm = nn.LayerNorm(in_features) + self.fc1 = nn.Linear(in_features, hidden_features) + self.fc2 = nn.Linear(hidden_features, out_features) + self.act = act_layer() + self.drop = nn.Dropout(drop) + + def forward(self, x): + x = self.norm(x) + + x = self.fc1(x) + x = self.act(x) + x = self.drop(x) + x = self.fc2(x) + x = self.drop(x) + return x + + +class Attention(torch.nn.Module): + def __init__( + self, + dim, + key_dim, + num_heads=8, + attn_ratio=4, + resolution=(14, 14), + ): + super().__init__() + # (h, w) + assert isinstance(resolution, tuple) and len(resolution) == 2 + self.num_heads = num_heads + self.scale = key_dim**-0.5 + self.key_dim = key_dim + self.nh_kd = nh_kd = key_dim * num_heads + self.d = int(attn_ratio * key_dim) + self.dh = int(attn_ratio * key_dim) * num_heads + self.attn_ratio = attn_ratio + h = self.dh + nh_kd * 2 + + self.norm = nn.LayerNorm(dim) + self.qkv = nn.Linear(dim, h) + self.proj = nn.Linear(self.dh, dim) + + points = list(itertools.product(range(resolution[0]), range(resolution[1]))) + N = len(points) + attention_offsets = {} + idxs = [] + for p1 in points: + for p2 in points: + offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1])) + if offset not in attention_offsets: + attention_offsets[offset] = len(attention_offsets) + idxs.append(attention_offsets[offset]) + self.attention_biases = torch.nn.Parameter( + torch.zeros(num_heads, len(attention_offsets)) + ) + self.register_buffer( + "attention_bias_idxs", torch.LongTensor(idxs).view(N, N), persistent=False + ) + + @torch.no_grad() + def train(self, mode=True): + super().train(mode) + if mode and hasattr(self, "ab"): + del self.ab + else: + self.register_buffer( + "ab", + self.attention_biases[:, self.attention_bias_idxs], + persistent=False, + ) + + def forward(self, x): # x (B,N,C) + B, N, _ = x.shape + + # Normalization + x = self.norm(x) + + qkv = self.qkv(x) + # (B, N, num_heads, d) + q, k, v = qkv.view(B, N, self.num_heads, -1).split( + [self.key_dim, self.key_dim, self.d], dim=3 + ) + # (B, num_heads, N, d) + q = q.permute(0, 2, 1, 3) + k = k.permute(0, 2, 1, 3) + v = v.permute(0, 2, 1, 3) + + attn = (q @ k.transpose(-2, -1)) * self.scale + ( + self.attention_biases[:, self.attention_bias_idxs] + if self.training + else self.ab + ) + attn = attn.softmax(dim=-1) + x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh) + x = self.proj(x) + return x + + +class TinyViTBlock(nn.Module): + r"""TinyViT Block. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int, int]): Input resolution. + num_heads (int): Number of attention heads. + window_size (int): Window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float, optional): Stochastic depth rate. Default: 0.0 + local_conv_size (int): the kernel size of the convolution between + Attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + """ + + def __init__( + self, + dim, + input_resolution, + num_heads, + window_size=7, + mlp_ratio=4.0, + drop=0.0, + drop_path=0.0, + local_conv_size=3, + activation=nn.GELU, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.num_heads = num_heads + assert window_size > 0, "window_size must be greater than 0" + self.window_size = window_size + self.mlp_ratio = mlp_ratio + + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + assert dim % num_heads == 0, "dim must be divisible by num_heads" + head_dim = dim // num_heads + + window_resolution = (window_size, window_size) + self.attn = Attention( + dim, head_dim, num_heads, attn_ratio=1, resolution=window_resolution + ) + + mlp_hidden_dim = int(dim * mlp_ratio) + mlp_activation = activation + self.mlp = Mlp( + in_features=dim, + hidden_features=mlp_hidden_dim, + act_layer=mlp_activation, + drop=drop, + ) + + pad = local_conv_size // 2 + self.local_conv = Conv2d_BN( + dim, dim, ks=local_conv_size, stride=1, pad=pad, groups=dim + ) + + def forward(self, x): + H, W = self.input_resolution + B, L, C = x.shape + assert L == H * W, "input feature has wrong size" + res_x = x + if H == self.window_size and W == self.window_size: + x = self.attn(x) + else: + x = x.view(B, H, W, C) + pad_b = (self.window_size - H % self.window_size) % self.window_size + pad_r = (self.window_size - W % self.window_size) % self.window_size + padding = pad_b > 0 or pad_r > 0 + + if padding: + x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b)) + + pH, pW = H + pad_b, W + pad_r + nH = pH // self.window_size + nW = pW // self.window_size + # window partition + x = ( + x.view(B, nH, self.window_size, nW, self.window_size, C) + .transpose(2, 3) + .reshape(B * nH * nW, self.window_size * self.window_size, C) + ) + x = self.attn(x) + # window reverse + x = ( + x.view(B, nH, nW, self.window_size, self.window_size, C) + .transpose(2, 3) + .reshape(B, pH, pW, C) + ) + + if padding: + x = x[:, :H, :W].contiguous() + + x = x.view(B, L, C) + + x = res_x + self.drop_path(x) + + x = x.transpose(1, 2).reshape(B, C, H, W) + x = self.local_conv(x) + x = x.view(B, C, L).transpose(1, 2) + + x = x + self.drop_path(self.mlp(x)) + return x + + def extra_repr(self) -> str: + return ( + f"dim={self.dim}, input_resolution={self.input_resolution}, num_heads={self.num_heads}, " + f"window_size={self.window_size}, mlp_ratio={self.mlp_ratio}" + ) + + +class BasicLayer(nn.Module): + """A basic TinyViT layer for one stage. + + Args: + dim (int): Number of input channels. + input_resolution (tuple[int]): Input resolution. + depth (int): Number of blocks. + num_heads (int): Number of attention heads. + window_size (int): Local window size. + mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. + drop (float, optional): Dropout rate. Default: 0.0 + drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0 + downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None + use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False. + local_conv_size: the kernel size of the depthwise convolution between attention and MLP. Default: 3 + activation: the activation function. Default: nn.GELU + out_dim: the output dimension of the layer. Default: dim + """ + + def __init__( + self, + dim, + input_resolution, + depth, + num_heads, + window_size, + mlp_ratio=4.0, + drop=0.0, + drop_path=0.0, + downsample=None, + use_checkpoint=False, + local_conv_size=3, + activation=nn.GELU, + out_dim=None, + ): + super().__init__() + self.dim = dim + self.input_resolution = input_resolution + self.depth = depth + self.use_checkpoint = use_checkpoint + + # build blocks + self.blocks = nn.ModuleList( + [ + TinyViTBlock( + dim=dim, + input_resolution=input_resolution, + num_heads=num_heads, + window_size=window_size, + mlp_ratio=mlp_ratio, + drop=drop, + drop_path=drop_path[i] + if isinstance(drop_path, list) + else drop_path, + local_conv_size=local_conv_size, + activation=activation, + ) + for i in range(depth) + ] + ) + + # patch merging layer + if downsample is not None: + self.downsample = downsample( + input_resolution, dim=dim, out_dim=out_dim, activation=activation + ) + else: + self.downsample = None + + def forward(self, x): + for blk in self.blocks: + if self.use_checkpoint: + x = checkpoint.checkpoint(blk, x) + else: + x = blk(x) + if self.downsample is not None: + x = self.downsample(x) + return x + + def extra_repr(self) -> str: + return f"dim={self.dim}, input_resolution={self.input_resolution}, depth={self.depth}" + + +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +class TinyViT(nn.Module): + def __init__( + self, + img_size=224, + in_chans=3, + num_classes=1000, + embed_dims=[96, 192, 384, 768], + depths=[2, 2, 6, 2], + num_heads=[3, 6, 12, 24], + window_sizes=[7, 7, 14, 7], + mlp_ratio=4.0, + drop_rate=0.0, + drop_path_rate=0.1, + use_checkpoint=False, + mbconv_expand_ratio=4.0, + local_conv_size=3, + layer_lr_decay=1.0, + ): + super().__init__() + self.img_size = img_size + self.num_classes = num_classes + self.depths = depths + self.num_layers = len(depths) + self.mlp_ratio = mlp_ratio + + activation = nn.GELU + + self.patch_embed = PatchEmbed( + in_chans=in_chans, + embed_dim=embed_dims[0], + resolution=img_size, + activation=activation, + ) + + patches_resolution = self.patch_embed.patches_resolution + self.patches_resolution = patches_resolution + + # stochastic depth + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, sum(depths)) + ] # stochastic depth decay rule + + # build layers + self.layers = nn.ModuleList() + for i_layer in range(self.num_layers): + kwargs = dict( + dim=embed_dims[i_layer], + input_resolution=( + patches_resolution[0] + // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + patches_resolution[1] + // (2 ** (i_layer - 1 if i_layer == 3 else i_layer)), + ), + # input_resolution=(patches_resolution[0] // (2 ** i_layer), + # patches_resolution[1] // (2 ** i_layer)), + depth=depths[i_layer], + drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])], + downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, + use_checkpoint=use_checkpoint, + out_dim=embed_dims[min(i_layer + 1, len(embed_dims) - 1)], + activation=activation, + ) + if i_layer == 0: + layer = ConvLayer( + conv_expand_ratio=mbconv_expand_ratio, + **kwargs, + ) + else: + layer = BasicLayer( + num_heads=num_heads[i_layer], + window_size=window_sizes[i_layer], + mlp_ratio=self.mlp_ratio, + drop=drop_rate, + local_conv_size=local_conv_size, + **kwargs, + ) + self.layers.append(layer) + + # Classifier head + self.norm_head = nn.LayerNorm(embed_dims[-1]) + self.head = ( + nn.Linear(embed_dims[-1], num_classes) + if num_classes > 0 + else torch.nn.Identity() + ) + + # init weights + self.apply(self._init_weights) + self.set_layer_lr_decay(layer_lr_decay) + self.neck = nn.Sequential( + nn.Conv2d( + embed_dims[-1], + 256, + kernel_size=1, + bias=False, + ), + LayerNorm2d(256), + nn.Conv2d( + 256, + 256, + kernel_size=3, + padding=1, + bias=False, + ), + LayerNorm2d(256), + ) + + def set_layer_lr_decay(self, layer_lr_decay): + decay_rate = layer_lr_decay + + # layers -> blocks (depth) + depth = sum(self.depths) + lr_scales = [decay_rate ** (depth - i - 1) for i in range(depth)] + # print("LR SCALES:", lr_scales) + + def _set_lr_scale(m, scale): + for p in m.parameters(): + p.lr_scale = scale + + self.patch_embed.apply(lambda x: _set_lr_scale(x, lr_scales[0])) + i = 0 + for layer in self.layers: + for block in layer.blocks: + block.apply(lambda x: _set_lr_scale(x, lr_scales[i])) + i += 1 + if layer.downsample is not None: + layer.downsample.apply(lambda x: _set_lr_scale(x, lr_scales[i - 1])) + assert i == depth + for m in [self.norm_head, self.head]: + m.apply(lambda x: _set_lr_scale(x, lr_scales[-1])) + + for k, p in self.named_parameters(): + p.param_name = k + + def _check_lr_scale(m): + for p in m.parameters(): + assert hasattr(p, "lr_scale"), p.param_name + + self.apply(_check_lr_scale) + + def _init_weights(self, m): + if isinstance(m, nn.Linear): + trunc_normal_(m.weight, std=0.02) + if isinstance(m, nn.Linear) and m.bias is not None: + nn.init.constant_(m.bias, 0) + elif isinstance(m, nn.LayerNorm): + nn.init.constant_(m.bias, 0) + nn.init.constant_(m.weight, 1.0) + + @torch.jit.ignore + def no_weight_decay_keywords(self): + return {"attention_biases"} + + def forward_features(self, x): + # x: (N, C, H, W) + x = self.patch_embed(x) + + x = self.layers[0](x) + start_i = 1 + + for i in range(start_i, len(self.layers)): + layer = self.layers[i] + x = layer(x) + B, _, C = x.size() + x = x.view(B, 64, 64, C) + x = x.permute(0, 3, 1, 2) + x = self.neck(x) + return x + + def forward(self, x): + x = self.forward_features(x) + # x = self.norm_head(x) + # x = self.head(x) + return x diff --git a/py/iopaint/plugins/segment_anything/modeling/transformer.py b/py/iopaint/plugins/segment_anything/modeling/transformer.py new file mode 100644 index 0000000..f1a2812 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/modeling/transformer.py @@ -0,0 +1,240 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch import Tensor, nn + +import math +from typing import Tuple, Type + +from .common import MLPBlock + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attenion layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLPBlock(embedding_dim, mlp_dim, activation) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim." + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(embedding_dim, self.internal_dim) + self.v_proj = nn.Linear(embedding_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Attention + _, _, _, c_per_head = q.shape + attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens + attn = attn / math.sqrt(c_per_head) + attn = torch.softmax(attn, dim=-1) + + # Get output + out = attn @ v + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/py/iopaint/plugins/segment_anything/predictor.py b/py/iopaint/plugins/segment_anything/predictor.py new file mode 100644 index 0000000..23d0649 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/predictor.py @@ -0,0 +1,285 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from .modeling import Sam + +from typing import Optional, Tuple + + +class SamPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + from .utils.transforms import ResizeLongestSide + + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[ + None, :, :, : + ] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + labels_torch = torch.as_tensor( + point_labels, dtype=torch.int, device=self.device + ) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor( + mask_input, dtype=torch.float, device=self.device + ) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + ) + + masks = masks[0].detach().cpu().numpy() + iou_predictions = iou_predictions[0].detach().cpu().numpy() + low_res_masks = low_res_masks[0].detach().cpu().numpy() + return masks, iou_predictions, low_res_masks + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks( + low_res_masks, self.input_size, self.original_size + ) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self.features is not None + ), "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/py/iopaint/plugins/segment_anything/predictor_hq.py b/py/iopaint/plugins/segment_anything/predictor_hq.py new file mode 100644 index 0000000..d8fd50f --- /dev/null +++ b/py/iopaint/plugins/segment_anything/predictor_hq.py @@ -0,0 +1,292 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch + +from .modeling import Sam + +from typing import Optional, Tuple + +from .utils.transforms import ResizeLongestSide + + +class SamHQPredictor: + def __init__( + self, + sam_model: Sam, + ) -> None: + """ + Uses SAM to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam): The model to use for mask prediction. + """ + super().__init__() + self.model = sam_model + self.transform = ResizeLongestSide(sam_model.image_encoder.img_size) + self.reset_image() + + def set_image( + self, + image: np.ndarray, + image_format: str = "RGB", + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + image (np.ndarray): The image for calculating masks. Expects an + image in HWC uint8 format, with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + assert image_format in [ + "RGB", + "BGR", + ], f"image_format must be in ['RGB', 'BGR'], is {image_format}." + # import pdb;pdb.set_trace() + if image_format != self.model.image_format: + image = image[..., ::-1] + + # Transform the image to the form expected by the model + # import pdb;pdb.set_trace() + input_image = self.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image, device=self.device) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[ + None, :, :, : + ] + + self.set_torch_image(input_image_torch, image.shape[:2]) + + @torch.no_grad() + def set_torch_image( + self, + transformed_image: torch.Tensor, + original_image_size: Tuple[int, ...], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. Expects the input + image to be already transformed to the format expected by the model. + + Arguments: + transformed_image (torch.Tensor): The input image, with shape + 1x3xHxW, which has been transformed with ResizeLongestSide. + original_image_size (tuple(int, int)): The size of the image + before transformation, in (H, W) format. + """ + assert ( + len(transformed_image.shape) == 4 + and transformed_image.shape[1] == 3 + and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size + ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}." + self.reset_image() + + self.original_size = original_image_size + self.input_size = tuple(transformed_image.shape[-2:]) + input_image = self.model.preprocess(transformed_image) + self.features, self.interm_features = self.model.image_encoder(input_image) + self.is_image_set = True + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + hq_token_only: bool = False, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None + if point_coords is not None: + assert ( + point_labels is not None + ), "point_labels must be supplied if point_coords is supplied." + point_coords = self.transform.apply_coords(point_coords, self.original_size) + coords_torch = torch.as_tensor( + point_coords, dtype=torch.float, device=self.device + ) + labels_torch = torch.as_tensor( + point_labels, dtype=torch.int, device=self.device + ) + coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :] + if box is not None: + box = self.transform.apply_boxes(box, self.original_size) + box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device) + box_torch = box_torch[None, :] + if mask_input is not None: + mask_input_torch = torch.as_tensor( + mask_input, dtype=torch.float, device=self.device + ) + mask_input_torch = mask_input_torch[None, :, :, :] + + masks, iou_predictions, low_res_masks = self.predict_torch( + coords_torch, + labels_torch, + box_torch, + mask_input_torch, + multimask_output, + return_logits=return_logits, + hq_token_only=hq_token_only, + ) + + masks_np = masks[0].detach().cpu().numpy() + iou_predictions_np = iou_predictions[0].detach().cpu().numpy() + low_res_masks_np = low_res_masks[0].detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + @torch.no_grad() + def predict_torch( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + hq_token_only: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using ResizeLongestSide. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + if point_coords is not None: + points = (point_coords, point_labels) + else: + points = None + + # Embed prompts + sparse_embeddings, dense_embeddings = self.model.prompt_encoder( + points=points, + boxes=boxes, + masks=mask_input, + ) + + # Predict masks + low_res_masks, iou_predictions = self.model.mask_decoder( + image_embeddings=self.features, + image_pe=self.model.prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + hq_token_only=hq_token_only, + interm_embeddings=self.interm_features, + ) + + # Upscale the masks to the original image resolution + masks = self.model.postprocess_masks( + low_res_masks, self.input_size, self.original_size + ) + + if not return_logits: + masks = masks > self.model.mask_threshold + + return masks, iou_predictions, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self.is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert ( + self.features is not None + ), "Features must exist if an image has been set." + return self.features + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_image(self) -> None: + """Resets the currently set image.""" + self.is_image_set = False + self.features = None + self.orig_h = None + self.orig_w = None + self.input_h = None + self.input_w = None diff --git a/py/iopaint/plugins/segment_anything/utils/__init__.py b/py/iopaint/plugins/segment_anything/utils/__init__.py new file mode 100644 index 0000000..5277f46 --- /dev/null +++ b/py/iopaint/plugins/segment_anything/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/py/iopaint/plugins/segment_anything/utils/transforms.py b/py/iopaint/plugins/segment_anything/utils/transforms.py new file mode 100644 index 0000000..90f50ed --- /dev/null +++ b/py/iopaint/plugins/segment_anything/utils/transforms.py @@ -0,0 +1,112 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import numpy as np +import torch +from torch.nn import functional as F +from torchvision.transforms.functional import resize, to_pil_image # type: ignore + +from copy import deepcopy +from typing import Tuple + + +class ResizeLongestSide: + """ + Resizes images to longest side 'target_length', as well as provides + methods for resizing coordinates and boxes. Provides methods for + transforming both numpy array and batched torch tensors. + """ + + def __init__(self, target_length: int) -> None: + self.target_length = target_length + + def apply_image(self, image: np.ndarray) -> np.ndarray: + """ + Expects a numpy array with shape HxWxC in uint8 format. + """ + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return np.array(resize(to_pil_image(image), target_size)) + + def apply_coords( + self, coords: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array of length 2 in the final dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).astype(float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes( + self, boxes: np.ndarray, original_size: Tuple[int, ...] + ) -> np.ndarray: + """ + Expects a numpy array shape Bx4. Requires the original image size + in (H, W) format. + """ + boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor: + """ + Expects batched images with shape BxCxHxW and float format. This + transformation may not exactly match apply_image. apply_image is + the transformation expected by the model. + """ + # Expects an image in BCHW format. May not exactly match apply_image. + target_size = self.get_preprocess_shape( + image.shape[0], image.shape[1], self.target_length + ) + return F.interpolate( + image, target_size, mode="bilinear", align_corners=False, antialias=True + ) + + def apply_coords_torch( + self, coords: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. Requires the + original image size in (H, W) format. + """ + old_h, old_w = original_size + new_h, new_w = self.get_preprocess_shape( + original_size[0], original_size[1], self.target_length + ) + coords = deepcopy(coords).to(torch.float) + coords[..., 0] = coords[..., 0] * (new_w / old_w) + coords[..., 1] = coords[..., 1] * (new_h / old_h) + return coords + + def apply_boxes_torch( + self, boxes: torch.Tensor, original_size: Tuple[int, ...] + ) -> torch.Tensor: + """ + Expects a torch tensor with shape Bx4. Requires the original image + size in (H, W) format. + """ + boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size) + return boxes.reshape(-1, 4) + + @staticmethod + def get_preprocess_shape( + oldh: int, oldw: int, long_side_length: int + ) -> Tuple[int, int]: + """ + Compute the output size given input size and target long side length. + """ + scale = long_side_length * 1.0 / max(oldh, oldw) + newh, neww = oldh * scale, oldw * scale + neww = int(neww + 0.5) + newh = int(newh + 0.5) + return (newh, neww) diff --git a/py/iopaint/runtime.py b/py/iopaint/runtime.py new file mode 100644 index 0000000..aa96f91 --- /dev/null +++ b/py/iopaint/runtime.py @@ -0,0 +1,88 @@ +# https://github.com/huggingface/huggingface_hub/blob/5a12851f54bf614be39614034ed3a9031922d297/src/huggingface_hub/utils/_runtime.py +import os +import platform +import sys +from pathlib import Path + +import packaging.version +from .schema import Device +from loguru import logger +from rich import print +from typing import Dict, Any + + +_PY_VERSION: str = sys.version.split()[0].rstrip("+") + +if packaging.version.Version(_PY_VERSION) < packaging.version.Version("3.8.0"): + import importlib_metadata # type: ignore +else: + import importlib.metadata as importlib_metadata # type: ignore + +_package_versions = {} + +_CANDIDATES = [ + "torch", + "torchvision", + "Pillow", + "diffusers", + "transformers", + "opencv-python", + "accelerate", + "iopaint", + "rembg", + "realesrgan", + "gfpgan", +] +# Check once at runtime +for name in _CANDIDATES: + _package_versions[name] = "N/A" + try: + _package_versions[name] = importlib_metadata.version(name) + except importlib_metadata.PackageNotFoundError: + pass + + +def dump_environment_info() -> Dict[str, str]: + """Dump information about the machine to help debugging issues.""" + + # Generic machine info + info: Dict[str, Any] = { + "Platform": platform.platform(), + "Python version": platform.python_version(), + } + info.update(_package_versions) + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()]) + "\n") + return info + + +def check_device(device: Device) -> Device: + if device == Device.cuda: + import platform + + if platform.system() == "Darwin": + logger.warning("MacOS does not support cuda, use cpu instead") + return Device.cpu + else: + import torch + + if not torch.cuda.is_available(): + logger.warning("CUDA is not available, use cpu instead") + return Device.cpu + elif device == Device.mps: + import torch + + if not torch.backends.mps.is_available(): + logger.warning("mps is not available, use cpu instead") + return Device.cpu + return device + + +def setup_model_dir(model_dir: Path): + model_dir = model_dir.expanduser().absolute() + logger.info(f"Model directory: {model_dir}") + os.environ["U2NET_HOME"] = str(model_dir) + os.environ["XDG_CACHE_HOME"] = str(model_dir) + if not model_dir.exists(): + logger.info(f"Create model directory: {model_dir}") + model_dir.mkdir(exist_ok=True, parents=True) + return model_dir diff --git a/py/iopaint/schema.py b/py/iopaint/schema.py new file mode 100644 index 0000000..7573286 --- /dev/null +++ b/py/iopaint/schema.py @@ -0,0 +1,470 @@ +import random +from enum import Enum +from pathlib import Path +from typing import Optional, Literal, List + +from .const import ( + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + SDXL_CONTROLNET_CHOICES, + SD2_CONTROLNET_CHOICES, + SD_CONTROLNET_CHOICES, +) +from loguru import logger +from pydantic import BaseModel, Field, field_validator, computed_field + + +class ModelType(str, Enum): + INPAINT = "inpaint" # LaMa, MAT... + DIFFUSERS_SD = "diffusers_sd" + DIFFUSERS_SD_INPAINT = "diffusers_sd_inpaint" + DIFFUSERS_SDXL = "diffusers_sdxl" + DIFFUSERS_SDXL_INPAINT = "diffusers_sdxl_inpaint" + DIFFUSERS_OTHER = "diffusers_other" + + +class ModelInfo(BaseModel): + name: str + path: str + model_type: ModelType + is_single_file_diffusers: bool = False + + @computed_field + @property + def need_prompt(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [ + INSTRUCT_PIX2PIX_NAME, + KANDINSKY22_NAME, + POWERPAINT_NAME, + ANYTEXT_NAME, + ] + + @computed_field + @property + def controlnets(self) -> List[str]: + if self.model_type in [ + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SDXL_INPAINT, + ]: + return SDXL_CONTROLNET_CHOICES + if self.model_type in [ModelType.DIFFUSERS_SD, ModelType.DIFFUSERS_SD_INPAINT]: + if "sd2" in self.name.lower(): + return SD2_CONTROLNET_CHOICES + else: + return SD_CONTROLNET_CHOICES + if self.name == POWERPAINT_NAME: + return SD_CONTROLNET_CHOICES + return [] + + @computed_field + @property + def support_strength(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [POWERPAINT_NAME, ANYTEXT_NAME] + + @computed_field + @property + def support_outpainting(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [KANDINSKY22_NAME, POWERPAINT_NAME] + + @computed_field + @property + def support_lcm_lora(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_controlnet(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] + + @computed_field + @property + def support_freeu(self) -> bool: + return self.model_type in [ + ModelType.DIFFUSERS_SD, + ModelType.DIFFUSERS_SDXL, + ModelType.DIFFUSERS_SD_INPAINT, + ModelType.DIFFUSERS_SDXL_INPAINT, + ] or self.name in [INSTRUCT_PIX2PIX_NAME] + + +class Choices(str, Enum): + @classmethod + def values(cls): + return [member.value for member in cls] + + +class RealESRGANModel(Choices): + realesr_general_x4v3 = "realesr-general-x4v3" + RealESRGAN_x4plus = "RealESRGAN_x4plus" + RealESRGAN_x4plus_anime_6B = "RealESRGAN_x4plus_anime_6B" + + +class RemoveBGModel(Choices): + u2net = "u2net" + u2netp = "u2netp" + u2net_human_seg = "u2net_human_seg" + u2net_cloth_seg = "u2net_cloth_seg" + silueta = "silueta" + isnet_general_use = "isnet-general-use" + briaai_rmbg_1_4 = "briaai/RMBG-1.4" + + +class Device(Choices): + cpu = "cpu" + cuda = "cuda" + mps = "mps" + + +class InteractiveSegModel(Choices): + vit_b = "vit_b" + vit_l = "vit_l" + vit_h = "vit_h" + sam_hq_vit_b = "sam_hq_vit_b" + sam_hq_vit_l = "sam_hq_vit_l" + sam_hq_vit_h = "sam_hq_vit_h" + mobile_sam = "mobile_sam" + + +class PluginInfo(BaseModel): + name: str + support_gen_image: bool = False + support_gen_mask: bool = False + + +class CV2Flag(str, Enum): + INPAINT_NS = "INPAINT_NS" + INPAINT_TELEA = "INPAINT_TELEA" + + +class HDStrategy(str, Enum): + # Use original image size + ORIGINAL = "Original" + # Resize the longer side of the image to a specific size(hd_strategy_resize_limit), + # then do inpainting on the resized image. Finally, resize the inpainting result to the original size. + # The area outside the mask will not lose quality. + RESIZE = "Resize" + # Crop masking area(with a margin controlled by hd_strategy_crop_margin) from the original image to do inpainting + CROP = "Crop" + + +class LDMSampler(str, Enum): + ddim = "ddim" + plms = "plms" + + +class SDSampler(str, Enum): + dpm_plus_plus_2m = "DPM++ 2M" + dpm_plus_plus_2m_karras = "DPM++ 2M Karras" + dpm_plus_plus_2m_sde = "DPM++ 2M SDE" + dpm_plus_plus_2m_sde_karras = "DPM++ 2M SDE Karras" + dpm_plus_plus_sde = "DPM++ SDE" + dpm_plus_plus_sde_karras = "DPM++ SDE Karras" + dpm2 = "DPM2" + dpm2_karras = "DPM2 Karras" + dpm2_a = "DPM2 a" + dpm2_a_karras = "DPM2 a Karras" + euler = "Euler" + euler_a = "Euler a" + heun = "Heun" + lms = "LMS" + lms_karras = "LMS Karras" + + ddim = "DDIM" + pndm = "PNDM" + uni_pc = "UniPC" + lcm = "LCM" + + +class FREEUConfig(BaseModel): + s1: float = 0.9 + s2: float = 0.2 + b1: float = 1.2 + b2: float = 1.4 + + +class PowerPaintTask(str, Enum): + text_guided = "text-guided" + shape_guided = "shape-guided" + object_remove = "object-remove" + outpainting = "outpainting" + + +class ApiConfig(BaseModel): + host: str + port: int + inbrowser: bool + model: str + no_half: bool + low_mem: bool + cpu_offload: bool + disable_nsfw_checker: bool + local_files_only: bool + cpu_textencoder: bool + device: Device + input: Optional[Path] + output_dir: Optional[Path] + quality: int + enable_interactive_seg: bool + interactive_seg_model: InteractiveSegModel + interactive_seg_device: Device + enable_remove_bg: bool + remove_bg_model: str + enable_anime_seg: bool + enable_realesrgan: bool + realesrgan_device: Device + realesrgan_model: RealESRGANModel + enable_gfpgan: bool + gfpgan_device: Device + enable_restoreformer: bool + restoreformer_device: Device + + +class InpaintRequest(BaseModel): + image: Optional[str] = Field(None, description="base64 encoded image") + mask: Optional[str] = Field(None, description="base64 encoded mask") + + ldm_steps: int = Field(20, description="Steps for ldm model.") + ldm_sampler: str = Field(LDMSampler.plms, discription="Sampler for ldm model.") + zits_wireframe: bool = Field(True, description="Enable wireframe for zits model.") + + hd_strategy: str = Field( + HDStrategy.CROP, + description="Different way to preprocess image, only used by erase models(e.g. lama/mat)", + ) + hd_strategy_crop_trigger_size: int = Field( + 800, + description="Crop trigger size for hd_strategy=CROP, if the longer side of the image is larger than this value, use crop strategy", + ) + hd_strategy_crop_margin: int = Field( + 128, description="Crop margin for hd_strategy=CROP" + ) + hd_strategy_resize_limit: int = Field( + 1280, description="Resize limit for hd_strategy=RESIZE" + ) + + prompt: str = Field("", description="Prompt for diffusion models.") + negative_prompt: str = Field( + "", description="Negative prompt for diffusion models." + ) + use_croper: bool = Field( + False, description="Crop image before doing diffusion inpainting" + ) + croper_x: int = Field(0, description="Crop x for croper") + croper_y: int = Field(0, description="Crop y for croper") + croper_height: int = Field(512, description="Crop height for croper") + croper_width: int = Field(512, description="Crop width for croper") + + use_extender: bool = Field( + False, description="Extend image before doing sd outpainting" + ) + extender_x: int = Field(0, description="Extend x for extender") + extender_y: int = Field(0, description="Extend y for extender") + extender_height: int = Field(640, description="Extend height for extender") + extender_width: int = Field(640, description="Extend width for extender") + + sd_scale: float = Field( + 1.0, + description="Resize the image before doing sd inpainting, the area outside the mask will not lose quality.", + gt=0.0, + le=1.0, + ) + sd_mask_blur: int = Field( + 11, + description="Blur the edge of mask area. The higher the number the smoother blend with the original image", + ) + sd_strength: float = Field( + 1.0, + description="Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image", + le=1.0, + ) + sd_steps: int = Field( + 50, + description="The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference.", + ) + sd_guidance_scale: float = Field( + 7.5, + help="Higher guidance scale encourages to generate images that are closely linked to the text prompt, usually at the expense of lower image quality.", + ) + sd_sampler: str = Field( + SDSampler.uni_pc, description="Sampler for diffusion model." + ) + sd_seed: int = Field( + 42, + description="Seed for diffusion model. -1 mean random seed", + validate_default=True, + ) + sd_match_histograms: bool = Field( + False, + description="Match histograms between inpainting area and original image.", + ) + + sd_outpainting_softness: float = Field(20.0) + sd_outpainting_space: float = Field(20.0) + + sd_freeu: bool = Field( + False, + description="Enable freeu mode. https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu", + ) + sd_freeu_config: FREEUConfig = FREEUConfig() + + sd_lcm_lora: bool = Field( + False, + description="Enable lcm-lora mode. https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm#texttoimage", + ) + + sd_keep_unmasked_area: bool = Field( + True, description="Keep unmasked area unchanged" + ) + + cv2_flag: CV2Flag = Field( + CV2Flag.INPAINT_NS, + description="Flag for opencv inpainting: https://docs.opencv.org/4.6.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca05e763003a805e6c11c673a9f4ba7d07", + ) + cv2_radius: int = Field( + 4, + description="Radius of a circular neighborhood of each point inpainted that is considered by the algorithm", + ) + + # Paint by Example + paint_by_example_example_image: Optional[str] = Field( + None, description="Base64 encoded example image for paint by example model" + ) + + # InstructPix2Pix + p2p_image_guidance_scale: float = Field(1.5, description="Image guidance scale") + + # ControlNet + enable_controlnet: bool = Field(False, description="Enable controlnet") + controlnet_conditioning_scale: float = Field( + 0.4, description="Conditioning scale", ge=0.0, le=1.0 + ) + controlnet_method: str = Field( + "lllyasviel/control_v11p_sd15_canny", description="Controlnet method" + ) + + # PowerPaint + powerpaint_task: PowerPaintTask = Field( + PowerPaintTask.text_guided, description="PowerPaint task" + ) + fitting_degree: float = Field( + 1.0, + description="Control the fitting degree of the generated objects to the mask shape.", + gt=0.0, + le=1.0, + ) + + @field_validator("sd_seed") + @classmethod + def sd_seed_validator(cls, v: int) -> int: + if v == -1: + return random.randint(1, 99999999) + return v + + @field_validator("controlnet_conditioning_scale") + @classmethod + def validate_field(cls, v: float, values): + use_extender = values.data["use_extender"] + enable_controlnet = values.data["enable_controlnet"] + if use_extender and enable_controlnet: + logger.info(f"Extender is enabled, set controlnet_conditioning_scale=0") + return 0 + return v + + @field_validator("sd_strength") + @classmethod + def validate_sd_strength(cls, v: float, values): + use_extender = values.data["use_extender"] + if use_extender: + logger.info(f"Extender is enabled, set sd_strength=1") + return 1.0 + return v + + +class RunPluginRequest(BaseModel): + name: str + image: str = Field(..., description="base64 encoded image") + clicks: List[List[int]] = Field( + [], description="Clicks for interactive seg, [[x,y,0/1], [x2,y2,0/1]]" + ) + scale: float = Field(2.0, description="Scale for upscaling") + + +MediaTab = Literal["input", "output"] + + +class MediasResponse(BaseModel): + name: str + height: int + width: int + ctime: float + mtime: float + + +class GenInfoResponse(BaseModel): + prompt: str = "" + negative_prompt: str = "" + + +class ServerConfigResponse(BaseModel): + plugins: List[PluginInfo] + modelInfos: List[ModelInfo] + removeBGModel: RemoveBGModel + removeBGModels: List[RemoveBGModel] + realesrganModel: RealESRGANModel + realesrganModels: List[RealESRGANModel] + interactiveSegModel: InteractiveSegModel + interactiveSegModels: List[InteractiveSegModel] + enableFileManager: bool + enableAutoSaving: bool + enableControlnet: bool + controlnetMethod: Optional[str] + disableModelSwitch: bool + isDesktop: bool + samplers: List[str] + + +class SwitchModelRequest(BaseModel): + name: str + + +class SwitchPluginModelRequest(BaseModel): + plugin_name: str + model_name: str + + +AdjustMaskOperate = Literal["expand", "shrink", "reverse"] + + +class AdjustMaskRequest(BaseModel): + mask: str = Field( + ..., description="base64 encoded mask. 255 means area to do inpaint" + ) + operate: AdjustMaskOperate = Field(..., description="expand/shrink/reverse") + kernel_size: int = Field(5, description="Kernel size for expanding mask") diff --git a/py/iopaint/tests/__init__.py b/py/iopaint/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/py/iopaint/tests/test_adjust_mask.py b/py/iopaint/tests/test_adjust_mask.py new file mode 100644 index 0000000..1f01713 --- /dev/null +++ b/py/iopaint/tests/test_adjust_mask.py @@ -0,0 +1,17 @@ +import cv2 +from iopaint.helper import adjust_mask +from iopaint.tests.utils import current_dir, save_dir + +mask_p = current_dir / "overture-creations-5sI6fQgYIuo_mask.png" + + +def test_adjust_mask(): + mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + res_mask = adjust_mask(mask, 0, "expand") + cv2.imwrite(str(save_dir / "adjust_mask_original.png"), res_mask) + res_mask = adjust_mask(mask, 40, "expand") + cv2.imwrite(str(save_dir / "adjust_mask_expand.png"), res_mask) + res_mask = adjust_mask(mask, 20, "shrink") + cv2.imwrite(str(save_dir / "adjust_mask_shrink.png"), res_mask) + res_mask = adjust_mask(mask, 20, "reverse") + cv2.imwrite(str(save_dir / "adjust_mask_reverse.png"), res_mask) diff --git a/py/iopaint/tests/test_anytext.py b/py/iopaint/tests/test_anytext.py new file mode 100644 index 0000000..996176f --- /dev/null +++ b/py/iopaint/tests/test_anytext.py @@ -0,0 +1,45 @@ +import os + +from iopaint.tests.utils import check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_anytext(device): + sd_steps = check_device(device) + model = ModelManager( + name="Sanster/AnyText", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt='Characters written in chalk on the blackboard that says "DADDY", best quality, extremely detailed,4k, HD, supper legible text, clear text edges, clear strokes, neat writing, no watermarks', + negative_prompt="low-res, bad anatomy, extra digit, fewer digits, cropped, worst quality, low quality, watermark, unreadable text, messy words, distorted text, disorganized writing, advertising picture", + sd_steps=sd_steps, + sd_guidance_scale=9.0, + sd_seed=66273235, + sd_match_histograms=True + ) + + assert_equal( + model, + cfg, + f"anytext.png", + img_p=current_dir / "anytext_ref.jpg", + mask_p=current_dir / "anytext_mask.jpg", + ) diff --git a/py/iopaint/tests/test_controlnet.py b/py/iopaint/tests/test_controlnet.py new file mode 100644 index 0000000..c271345 --- /dev/null +++ b/py/iopaint/tests/test_controlnet.py @@ -0,0 +1,118 @@ +import os + +from iopaint.const import SD_CONTROLNET_CHOICES +from iopaint.tests.utils import current_dir, check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, SDSampler + + +model_name = "runwayml/stable-diffusion-inpainting" + + +def convert_controlnet_method_name(name): + return name.replace("/", "--") + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("controlnet_method", [SD_CONTROLNET_CHOICES[0]]) +def test_runway_sd_1_5(device, controlnet_method): + sd_steps = check_device(device) + + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=device == "cuda", + enable_controlnet=True, + controlnet_method=controlnet_method, + ) + + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + enable_controlnet=True, + controlnet_conditioning_scale=0.5, + controlnet_method=controlnet_method, + ) + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"sd_controlnet_{convert_controlnet_method_name(controlnet_method)}_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +def test_controlnet_switch(device): + sd_steps = check_device(device) + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + ) + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11f1p_sd15_depth", + ) + + assert_equal( + model, + cfg, + f"controlnet_switch_canny_to_depth_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.2 + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "local_file", ["sd-v1-5-inpainting.ckpt", "v1-5-pruned-emaonly.safetensors"] +) +def test_local_file_path(device, local_file): + sd_steps = check_device(device) + + controlnet_kwargs = dict( + enable_controlnet=True, + controlnet_method=SD_CONTROLNET_CHOICES[0], + ) + + model = ModelManager( + name=local_file, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + **controlnet_kwargs, + ) + cfg = get_config( + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + **controlnet_kwargs, + ) + + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"{convert_controlnet_method_name(controlnet_kwargs['controlnet_method'])}_local_model_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_instruct_pix2pix.py b/py/iopaint/tests/test_instruct_pix2pix.py new file mode 100644 index 0000000..f1ab4e2 --- /dev/null +++ b/py/iopaint/tests/test_instruct_pix2pix.py @@ -0,0 +1,40 @@ +from pathlib import Path + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy +from iopaint.tests.utils import get_config, check_device, assert_equal, current_dir + +model_name = "timbrooks/instruct-pix2pix" + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("disable_nsfw", [True, False]) +@pytest.mark.parametrize("cpu_offload", [False, True]) +def test_instruct_pix2pix(device, disable_nsfw, cpu_offload): + sd_steps = check_device(device) + model = ModelManager( + name=model_name, + device=torch.device(device), + disable_nsfw=disable_nsfw, + sd_cpu_textencoder=False, + cpu_offload=cpu_offload, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="What if it were snowing?", + sd_steps=sd_steps + ) + + name = f"device_{device}_disnsfw_{disable_nsfw}_cpu_offload_{cpu_offload}" + + assert_equal( + model, + cfg, + f"instruct_pix2pix_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.3, + ) diff --git a/py/iopaint/tests/test_load_img.py b/py/iopaint/tests/test_load_img.py new file mode 100644 index 0000000..f7071bf --- /dev/null +++ b/py/iopaint/tests/test_load_img.py @@ -0,0 +1,19 @@ +from iopaint.helper import load_img +from iopaint.tests.utils import current_dir + +png_img_p = current_dir / "image.png" +jpg_img_p = current_dir / "bunny.jpeg" + + +def test_load_png_image(): + with open(png_img_p, "rb") as f: + np_img, alpha_channel = load_img(f.read()) + assert np_img.shape == (256, 256, 3) + assert alpha_channel.shape == (256, 256) + + +def test_load_jpg_image(): + with open(jpg_img_p, "rb") as f: + np_img, alpha_channel = load_img(f.read()) + assert np_img.shape == (394, 448, 3) + assert alpha_channel is None diff --git a/py/iopaint/tests/test_low_mem.py b/py/iopaint/tests/test_low_mem.py new file mode 100644 index 0000000..70e8801 --- /dev/null +++ b/py/iopaint/tests/test_low_mem.py @@ -0,0 +1,131 @@ +import os + +from loguru import logger + +from iopaint.tests.utils import check_device, get_config, assert_equal, current_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, SDSampler, FREEUConfig + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_runway_sd_1_5_low_mem(device): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + + all_samplers = [member.value for member in SDSampler.__members__.values()] + print(all_samplers) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=SDSampler.ddim, + ) + + name = f"device_{device}" + + assert_equal( + model, + cfg, + f"runway_sd_{name}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.lcm]) +def test_runway_sd_lcm_lora_low_mem(device, sampler): + check_device(device) + + sd_steps = 5 + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=2, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_lcm_lora_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_freeu(device, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_freeu_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_norm_sd_model(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-v1-5", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True, + ) + cfg = get_config( + strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_{device}_norm_sd_model_device_{device}_low_mem.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_match_histograms.py b/py/iopaint/tests/test_match_histograms.py new file mode 100644 index 0000000..c20a283 --- /dev/null +++ b/py/iopaint/tests/test_match_histograms.py @@ -0,0 +1,36 @@ +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import SDSampler, HDStrategy +from iopaint.tests.utils import check_device, get_config, assert_equal, current_dir + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sd_match_histograms(device, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_lcm_lora=False, + sd_match_histograms=True, + sd_sampler=sampler + ) + + assert_equal( + model, + cfg, + f"runway_sd_1_5_device_{device}_match_histograms.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_model.py b/py/iopaint/tests/test_model.py new file mode 100644 index 0000000..dd84b12 --- /dev/null +++ b/py/iopaint/tests/test_model.py @@ -0,0 +1,160 @@ +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, LDMSampler +from iopaint.tests.utils import assert_equal, get_config, current_dir, check_device + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +def test_lama(device, strategy): + check_device(device) + model = ModelManager(name="lama", device=device) + assert_equal( + model, + get_config(strategy=strategy), + f"lama_{strategy[0].upper() + strategy[1:]}_result.png", + ) + + fx = 1.3 + assert_equal( + model, + get_config(strategy=strategy), + f"lama_{strategy[0].upper() + strategy[1:]}_fx_{fx}_result.png", + fx=1.3, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("ldm_sampler", [LDMSampler.ddim, LDMSampler.plms]) +def test_ldm(device, strategy, ldm_sampler): + check_device(device) + model = ModelManager(name="ldm", device=device) + cfg = get_config(strategy=strategy, ldm_sampler=ldm_sampler) + assert_equal( + model, cfg, f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_result.png" + ) + + fx = 1.3 + assert_equal( + model, + cfg, + f"ldm_{strategy[0].upper() + strategy[1:]}_{ldm_sampler}_fx_{fx}_result.png", + fx=fx, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("zits_wireframe", [False, True]) +def test_zits(device, strategy, zits_wireframe): + check_device(device) + model = ModelManager(name="zits", device=device) + cfg = get_config(strategy=strategy, zits_wireframe=zits_wireframe) + assert_equal( + model, + cfg, + f"zits_{strategy[0].upper() + strategy[1:]}_wireframe_{zits_wireframe}_result.png", + ) + + fx = 1.3 + assert_equal( + model, + cfg, + f"zits_{strategy.capitalize()}_wireframe_{zits_wireframe}_fx_{fx}_result.png", + fx=fx, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("no_half", [True, False]) +def test_mat(device, strategy, no_half): + check_device(device) + model = ModelManager(name="mat", device=device, no_half=no_half) + cfg = get_config(strategy=strategy) + + assert_equal( + model, + cfg, + f"mat_{strategy.capitalize()}_result.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +def test_fcf(device, strategy): + check_device(device) + model = ModelManager(name="fcf", device=device) + cfg = get_config(strategy=strategy) + + assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=2, fy=2) + assert_equal(model, cfg, f"fcf_{strategy.capitalize()}_result.png", fx=3.8, fy=2) + + +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +@pytest.mark.parametrize("cv2_flag", ["INPAINT_NS", "INPAINT_TELEA"]) +@pytest.mark.parametrize("cv2_radius", [3, 15]) +def test_cv2(strategy, cv2_flag, cv2_radius): + model = ModelManager( + name="cv2", + device=torch.device("cpu"), + ) + cfg = get_config(strategy=strategy, cv2_flag=cv2_flag, cv2_radius=cv2_radius) + assert_equal( + model, + cfg, + f"cv2_{strategy.capitalize()}_{cv2_flag}_{cv2_radius}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize( + "strategy", [HDStrategy.ORIGINAL, HDStrategy.RESIZE, HDStrategy.CROP] +) +def test_manga(device, strategy): + check_device(device) + model = ModelManager( + name="manga", + device=torch.device(device), + ) + cfg = get_config(strategy=strategy) + assert_equal( + model, + cfg, + f"manga_{strategy.capitalize()}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +def test_mi_gan(device, strategy): + check_device(device) + model = ModelManager( + name="migan", + device=torch.device(device), + ) + cfg = get_config(strategy=strategy) + assert_equal( + model, + cfg, + f"migan_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5, + fy=1.7 + ) diff --git a/py/iopaint/tests/test_model_md5.py b/py/iopaint/tests/test_model_md5.py new file mode 100644 index 0000000..3a81d72 --- /dev/null +++ b/py/iopaint/tests/test_model_md5.py @@ -0,0 +1,16 @@ +def test_load_model(): + from iopaint.plugins import InteractiveSeg + from iopaint.model_manager import ModelManager + + interactive_seg_model = InteractiveSeg("vit_l", "cpu") + + models = ["lama", "ldm", "zits", "mat", "fcf", "manga", "migan"] + for m in models: + ModelManager( + name=m, + device="cpu", + no_half=False, + disable_nsfw=False, + sd_cpu_textencoder=True, + cpu_offload=True, + ) diff --git a/py/iopaint/tests/test_model_switch.py b/py/iopaint/tests/test_model_switch.py new file mode 100644 index 0000000..735e1bd --- /dev/null +++ b/py/iopaint/tests/test_model_switch.py @@ -0,0 +1,70 @@ +import os + +from iopaint.schema import InpaintRequest + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import torch + +from iopaint.model_manager import ModelManager + + +def test_model_switch(): + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch("lama") + + +def test_controlnet_switch_onoff(caplog): + name = "runwayml/stable-diffusion-inpainting" + model = ModelManager( + name=name, + enable_controlnet=True, + controlnet_method="lllyasviel/control_v11p_sd15_canny", + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch_controlnet_method( + InpaintRequest( + name=name, + enable_controlnet=False, + ) + ) + + assert "Disable controlnet" in caplog.text + + +def test_switch_controlnet_method(caplog): + name = "runwayml/stable-diffusion-inpainting" + old_method = "lllyasviel/control_v11p_sd15_canny" + new_method = "lllyasviel/control_v11p_sd15_openpose" + model = ModelManager( + name=name, + enable_controlnet=True, + controlnet_method=old_method, + device=torch.device("mps"), + disable_nsfw=True, + sd_cpu_textencoder=True, + cpu_offload=False, + ) + + model.switch_controlnet_method( + InpaintRequest( + name=name, + enable_controlnet=True, + controlnet_method=new_method, + ) + ) + + assert f"Switch Controlnet method from {old_method} to {new_method}" in caplog.text diff --git a/py/iopaint/tests/test_outpainting.py b/py/iopaint/tests/test_outpainting.py new file mode 100644 index 0000000..024d701 --- /dev/null +++ b/py/iopaint/tests/test_outpainting.py @@ -0,0 +1,138 @@ +import os + +from iopaint.tests.utils import current_dir, check_device + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, SDSampler +from iopaint.tests.test_model import get_config, assert_equal + + +@pytest.mark.parametrize("name", ["runwayml/stable-diffusion-inpainting"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [0, -100, 512, 512 - 128 + 100], + [0, 128, 512, 512 - 128 + 100], + [128, 0, 512 - 128 + 100, 512], + [-100, 0, 512 - 128 + 100, 512], + [0, 0, 512, 512 + 200], + [0, 0, 512 + 200, 512], + [-100, -100, 512 + 200, 512 + 200], + ], +) +def test_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=8.0, + sd_sampler=SDSampler.dpm_plus_plus_2m, + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("name", ["kandinsky-community/kandinsky-2-2-decoder-inpaint"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [-128, -128, 768, 768], + ], +) +def test_kandinsky_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + prompt="a cat", + negative_prompt="lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=7, + sd_sampler=SDSampler.dpm_plus_plus_2m, + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "cat.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1, + fy=1, + ) + + +@pytest.mark.parametrize("name", ["Sanster/PowerPaint-V1-stable-diffusion-inpainting"]) +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize( + "rect", + [ + [-100, -100, 512 + 200, 512 + 200], + ], +) +def test_powerpaint_outpainting(name, device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + low_mem=True + ) + cfg = get_config( + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_guidance_scale=8.0, + sd_sampler=SDSampler.dpm_plus_plus_2m, + powerpaint_task="outpainting", + ) + + assert_equal( + model, + cfg, + f"{name.replace('/', '--')}_outpainting_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) diff --git a/py/iopaint/tests/test_paint_by_example.py b/py/iopaint/tests/test_paint_by_example.py new file mode 100644 index 0000000..27b8a77 --- /dev/null +++ b/py/iopaint/tests/test_paint_by_example.py @@ -0,0 +1,55 @@ +import cv2 +import pytest +from PIL import Image + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy +from iopaint.tests.utils import ( + current_dir, + get_config, + get_data, + save_dir, + check_device, +) + +model_name = "Fantasy-Studio/Paint-by-Example" + + +def assert_equal( + model, + config, + save_name: str, + fx: float = 1, + fy: float = 1, + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + example_p=current_dir / "bunny.jpeg", +): + img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p) + + example_image = cv2.imread(str(example_p)) + example_image = cv2.cvtColor(example_image, cv2.COLOR_BGRA2RGB) + example_image = cv2.resize( + example_image, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA + ) + + print(f"Input image shape: {img.shape}, example_image: {example_image.shape}") + config.paint_by_example_example_image = Image.fromarray(example_image) + res = model(img, mask, config) + cv2.imwrite(str(save_dir / save_name), res) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +def test_paint_by_example(device): + sd_steps = check_device(device) + model = ModelManager(name=model_name, device=device, disable_nsfw=True) + cfg = get_config(strategy=HDStrategy.ORIGINAL, sd_steps=sd_steps) + assert_equal( + model, + cfg, + f"paint_by_example_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fy=0.9, + fx=1.3, + ) diff --git a/py/iopaint/tests/test_plugins.py b/py/iopaint/tests/test_plugins.py new file mode 100644 index 0000000..aa7d367 --- /dev/null +++ b/py/iopaint/tests/test_plugins.py @@ -0,0 +1,121 @@ +import hashlib +import os +import time +from PIL import Image + +from iopaint.helper import encode_pil_to_base64, gen_frontend_mask +from iopaint.plugins.anime_seg import AnimeSeg +from iopaint.schema import RunPluginRequest, RemoveBGModel, InteractiveSegModel +from iopaint.tests.utils import check_device, current_dir, save_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import cv2 +import pytest + +from iopaint.plugins import ( + RemoveBG, + RealESRGANUpscaler, + GFPGANPlugin, + RestoreFormerPlugin, + InteractiveSeg, +) + +img_p = current_dir / "bunny.jpeg" +img_bytes = open(img_p, "rb").read() +bgr_img = cv2.imread(str(img_p)) +rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB) +rgb_img_base64 = encode_pil_to_base64(Image.fromarray(rgb_img), 100, {}) +bgr_img_base64 = encode_pil_to_base64(Image.fromarray(bgr_img), 100, {}) + + +def _save(img, name): + cv2.imwrite(str(save_dir / name), img) + + +def test_remove_bg(): + model = RemoveBG(RemoveBGModel.briaai_rmbg_1_4) + rgba_np_img = model.gen_image( + rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64) + ) + res = cv2.cvtColor(rgba_np_img, cv2.COLOR_RGBA2BGRA) + _save(res, "test_remove_bg.png") + + bgr_np_img = model.gen_mask( + rgb_img, RunPluginRequest(name=RemoveBG.name, image=rgb_img_base64) + ) + + res_mask = gen_frontend_mask(bgr_np_img) + _save(res_mask, "test_remove_bg_frontend_mask.png") + + assert len(bgr_np_img.shape) == 2 + _save(bgr_np_img, "test_remove_bg_mask.jpeg") + + +def test_anime_seg(): + model = AnimeSeg() + img = cv2.imread(str(current_dir / "anime_test.png")) + img_base64 = encode_pil_to_base64(Image.fromarray(img), 100, {}) + res = model.gen_image(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64)) + assert len(res.shape) == 3 + assert res.shape[-1] == 4 + _save(res, "test_anime_seg.png") + + res = model.gen_mask(img, RunPluginRequest(name=AnimeSeg.name, image=img_base64)) + assert len(res.shape) == 2 + _save(res, "test_anime_seg_mask.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_upscale(device): + check_device(device) + model = RealESRGANUpscaler("realesr-general-x4v3", device) + res = model.gen_image( + rgb_img, + RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=2), + ) + _save(res, f"test_upscale_x2_{device}.png") + + res = model.gen_image( + rgb_img, + RunPluginRequest(name=RealESRGANUpscaler.name, image=rgb_img_base64, scale=4), + ) + _save(res, f"test_upscale_x4_{device}.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_gfpgan(device): + check_device(device) + model = GFPGANPlugin(device) + res = model.gen_image( + rgb_img, RunPluginRequest(name=GFPGANPlugin.name, image=rgb_img_base64) + ) + _save(res, f"test_gfpgan_{device}.png") + + +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_restoreformer(device): + check_device(device) + model = RestoreFormerPlugin(device) + res = model.gen_image( + rgb_img, RunPluginRequest(name=RestoreFormerPlugin.name, image=rgb_img_base64) + ) + _save(res, f"test_restoreformer_{device}.png") + + +@pytest.mark.parametrize("name", InteractiveSegModel.values()) +@pytest.mark.parametrize("device", ["cuda", "cpu", "mps"]) +def test_segment_anything(name, device): + check_device(device) + model = InteractiveSeg(name, device) + new_mask = model.gen_mask( + rgb_img, + RunPluginRequest( + name=InteractiveSeg.name, + image=rgb_img_base64, + clicks=([[448 // 2, 394 // 2, 1]]), + ), + ) + + save_name = f"test_segment_anything_{name}_{device}.png" + _save(new_mask, save_name) diff --git a/py/iopaint/tests/test_save_exif.py b/py/iopaint/tests/test_save_exif.py new file mode 100644 index 0000000..5c19810 --- /dev/null +++ b/py/iopaint/tests/test_save_exif.py @@ -0,0 +1,59 @@ +import io +import tempfile +from pathlib import Path +from typing import List + +from PIL import Image + +from iopaint.helper import pil_to_bytes, load_img + +current_dir = Path(__file__).parent.absolute().resolve() + + +def print_exif(exif): + for k, v in exif.items(): + print(f"{k}: {v}") + + +def extra_info(img_p: Path): + ext = img_p.suffix.strip(".") + img_bytes = img_p.read_bytes() + np_img, _, infos = load_img(img_bytes, False, True) + res_pil_bytes = pil_to_bytes(Image.fromarray(np_img), ext=ext, infos=infos) + res_img = Image.open(io.BytesIO(res_pil_bytes)) + return infos, res_img.info, res_pil_bytes + + +def assert_keys(keys: List[str], infos, res_infos): + for k in keys: + assert k in infos + assert k in res_infos + assert infos[k] == res_infos[k] + + +def run_test(file_path, keys): + infos, res_infos, res_pil_bytes = extra_info(file_path) + assert_keys(keys, infos, res_infos) + with tempfile.NamedTemporaryFile("wb", suffix=file_path.suffix) as temp_file: + temp_file.write(res_pil_bytes) + temp_file.flush() + infos, res_infos, res_pil_bytes = extra_info(Path(temp_file.name)) + assert_keys(keys, infos, res_infos) + + +def test_png_icc_profile_png(): + run_test(current_dir / "icc_profile_test.png", ["icc_profile", "exif"]) + + +def test_png_icc_profile_jpeg(): + run_test(current_dir / "icc_profile_test.jpg", ["icc_profile", "exif"]) + + +def test_jpeg(): + jpg_img_p = current_dir / "bunny.jpeg" + run_test(jpg_img_p, ["dpi", "exif"]) + + +def test_png_parameter(): + jpg_img_p = current_dir / "png_parameter_test.png" + run_test(jpg_img_p, ["parameters"]) diff --git a/py/iopaint/tests/test_sd_model.py b/py/iopaint/tests/test_sd_model.py new file mode 100644 index 0000000..aa26c71 --- /dev/null +++ b/py/iopaint/tests/test_sd_model.py @@ -0,0 +1,269 @@ +import os + +from loguru import logger + +from iopaint.tests.utils import check_device, get_config, assert_equal + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" +from pathlib import Path + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, SDSampler, FREEUConfig + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +def test_runway_sd_1_5_all_samplers(device): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + all_samplers = [member.value for member in SDSampler.__members__.values()] + print(all_samplers) + for sampler in all_samplers: + print(f"Testing sampler {sampler}") + if ( + sampler + in [SDSampler.dpm2_karras, SDSampler.dpm2_a_karras, SDSampler.lms_karras] + and device == "mps" + ): + # diffusers 0.25.0 still has bug on these sampler on mps, wait main branch released to fix it + logger.warning( + "skip dpm2_karras on mps, diffusers does not support it on mps. TypeError: Cannot convert a MPS Tensor to float64 dtype as the MPS framework doesn't support float64. Please use float32 instead." + ) + continue + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=sampler, + ) + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"runway_sd_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.lcm]) +def test_runway_sd_lcm_lora(device, sampler): + check_device(device) + + sd_steps = 5 + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=2, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_lcm_lora_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_freeu(device, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_1_5_freeu_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_sd_strength(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_strength=0.8, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_sd_strength_0.8_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_sd_cpu_textencoder(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + cfg = get_config( + strategy=strategy, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + sd_sampler=sampler, + ) + + assert_equal( + model, + cfg, + f"runway_sd_device_{device}_cpu_textencoder.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_runway_norm_sd_model(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-v1-5", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, prompt="face of a fox, sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"runway_{device}_norm_sd_model_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.dpm_plus_plus_2m]) +def test_runway_sd_1_5_cpu_offload(device, strategy, sampler): + sd_steps = check_device(device) + model = ModelManager( + name="runwayml/stable-diffusion-inpainting", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=True, + ) + cfg = get_config( + strategy=strategy, prompt="a fox sitting on a bench", sd_steps=sd_steps + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"runway_sd_{strategy.capitalize()}_{name}_cpu_offload.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps", "cpu"]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +@pytest.mark.parametrize( + "name", + [ + "sd-v1-5-inpainting.safetensors", + "v1-5-pruned-emaonly.safetensors", + "sd_xl_base_1.0.safetensors", + "sd_xl_base_1.0_inpainting_0.1.safetensors", + ], +) +def test_local_file_path(device, sampler, name): + sd_steps = check_device(device) + model = ModelManager( + name=name, + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + cpu_offload=False, + ) + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a fox sitting on a bench", + sd_steps=sd_steps, + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}_{name}" + + is_sdxl = "sd_xl" in name + + assert_equal( + model, + cfg, + f"sd_local_model_{name}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5 if is_sdxl else 1, + fy=1.5 if is_sdxl else 1, + ) diff --git a/py/iopaint/tests/test_sdxl.py b/py/iopaint/tests/test_sdxl.py new file mode 100644 index 0000000..e236948 --- /dev/null +++ b/py/iopaint/tests/test_sdxl.py @@ -0,0 +1,172 @@ +import os + +from iopaint.tests.utils import check_device, current_dir + +os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + +import pytest +import torch + +from iopaint.model_manager import ModelManager +from iopaint.schema import HDStrategy, SDSampler, FREEUConfig +from iopaint.tests.test_model import get_config, assert_equal + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=7.0, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"sdxl_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "cpu"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl_cpu_text_encoder(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=True, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=7.0, + ) + cfg.sd_sampler = sampler + + assert_equal( + model, + cfg, + f"sdxl_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize("strategy", [HDStrategy.ORIGINAL]) +@pytest.mark.parametrize("sampler", [SDSampler.ddim]) +def test_sdxl_lcm_lora_and_freeu(device, strategy, sampler): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_strength=1.0, + sd_guidance_scale=2.0, + sd_lcm_lora=True, + ) + cfg.sd_sampler = sampler + + name = f"device_{device}_{sampler}" + + assert_equal( + model, + cfg, + f"sdxl_{name}_lcm_lora.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + cfg = get_config( + strategy=strategy, + prompt="face of a fox, sitting on a bench", + sd_steps=sd_steps, + sd_guidance_scale=7.5, + sd_freeu=True, + sd_freeu_config=FREEUConfig(), + ) + + assert_equal( + model, + cfg, + f"sdxl_{name}_freeu_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=2, + fy=2, + ) + + +@pytest.mark.parametrize("device", ["cuda", "mps"]) +@pytest.mark.parametrize( + "rect", + [ + [-128, -128, 1024, 1024], + ], +) +def test_sdxl_outpainting(device, rect): + sd_steps = check_device(device) + + model = ModelManager( + name="diffusers/stable-diffusion-xl-1.0-inpainting-0.1", + device=torch.device(device), + disable_nsfw=True, + sd_cpu_textencoder=False, + ) + + cfg = get_config( + strategy=HDStrategy.ORIGINAL, + prompt="a dog sitting on a bench in the park", + sd_steps=sd_steps, + use_extender=True, + extender_x=rect[0], + extender_y=rect[1], + extender_width=rect[2], + extender_height=rect[3], + sd_strength=1.0, + sd_guidance_scale=8.0, + sd_sampler=SDSampler.ddim, + ) + + assert_equal( + model, + cfg, + f"sdxl_outpainting_dog_ddim_{'_'.join(map(str, rect))}_device_{device}.png", + img_p=current_dir / "overture-creations-5sI6fQgYIuo.png", + mask_p=current_dir / "overture-creations-5sI6fQgYIuo_mask.png", + fx=1.5, + fy=1.5, + ) diff --git a/py/iopaint/tests/utils.py b/py/iopaint/tests/utils.py new file mode 100644 index 0000000..08f4aeb --- /dev/null +++ b/py/iopaint/tests/utils.py @@ -0,0 +1,77 @@ +from pathlib import Path +import cv2 +import pytest +import torch + +from iopaint.helper import encode_pil_to_base64 +from iopaint.schema import LDMSampler, HDStrategy, InpaintRequest, SDSampler +from PIL import Image + +current_dir = Path(__file__).parent.absolute().resolve() +save_dir = current_dir / "result" +save_dir.mkdir(exist_ok=True, parents=True) + + +def check_device(device: str) -> int: + if device == "cuda" and not torch.cuda.is_available(): + pytest.skip("CUDA is not available, skip test on cuda") + if device == "mps" and not torch.backends.mps.is_available(): + pytest.skip("mps is not available, skip test on mps") + steps = 2 if device == "cpu" else 20 + return steps + + +def assert_equal( + model, + config: InpaintRequest, + gt_name, + fx: float = 1, + fy: float = 1, + img_p=current_dir / "image.png", + mask_p=current_dir / "mask.png", +): + img, mask = get_data(fx=fx, fy=fy, img_p=img_p, mask_p=mask_p) + print(f"Input image shape: {img.shape}") + res = model(img, mask, config) + ok = cv2.imwrite( + str(save_dir / gt_name), + res, + [int(cv2.IMWRITE_JPEG_QUALITY), 100, int(cv2.IMWRITE_PNG_COMPRESSION), 0], + ) + assert ok, save_dir / gt_name + + """ + Note that JPEG is lossy compression, so even if it is the highest quality 100, + when the saved images is reloaded, a difference occurs with the original pixel value. + If you want to save the original images as it is, save it as PNG or BMP. + """ + # gt = cv2.imread(str(current_dir / gt_name), cv2.IMREAD_UNCHANGED) + # assert np.array_equal(res, gt) + + +def get_data( + fx: float = 1, + fy: float = 1.0, + img_p=current_dir / "image.png", + mask_p=current_dir / "mask.png", +): + img = cv2.imread(str(img_p)) + img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB) + mask = cv2.imread(str(mask_p), cv2.IMREAD_GRAYSCALE) + img = cv2.resize(img, None, fx=fx, fy=fy, interpolation=cv2.INTER_AREA) + mask = cv2.resize(mask, None, fx=fx, fy=fy, interpolation=cv2.INTER_NEAREST) + return img, mask + + +def get_config(**kwargs): + data = dict( + sd_sampler=kwargs.get("sd_sampler", SDSampler.uni_pc), + ldm_steps=1, + ldm_sampler=LDMSampler.plms, + hd_strategy=kwargs.get("strategy", HDStrategy.ORIGINAL), + hd_strategy_crop_margin=32, + hd_strategy_crop_trigger_size=200, + hd_strategy_resize_limit=200, + ) + data.update(**kwargs) + return InpaintRequest(image="", mask="", **data) diff --git a/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 b/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 new file mode 100644 index 0000000..18b35db Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Black-jiII8dog.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 b/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 new file mode 100644 index 0000000..02c9d8e Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-BlackItalic-1413vuen.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 b/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 new file mode 100644 index 0000000..0f1b157 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Bold-srYz_-1B.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 b/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 new file mode 100644 index 0000000..bc50f24 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-BoldItalic-dE_gZyur.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 b/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 new file mode 100644 index 0000000..b113368 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraBold-TduDdwUu.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 b/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 new file mode 100644 index 0000000..a5b76ca Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 b/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 new file mode 100644 index 0000000..1d77ae8 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraLight-w5HAp5iF.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 b/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 new file mode 100644 index 0000000..8c68492 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ExtraLightItalic-ZptecSuc.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 b/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 new file mode 100644 index 0000000..4c24ce2 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Italic-f6M78thn.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 b/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 new file mode 100644 index 0000000..dbe6143 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Light-DFhX0qo-.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 b/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 new file mode 100644 index 0000000..a40d042 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-LightItalic-fu56_DRc.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 b/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 new file mode 100644 index 0000000..0fd2ee7 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Medium-dDRaJ8tM.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 b/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 new file mode 100644 index 0000000..9676715 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-MediumItalic-zr3roggP.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 b/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 new file mode 100644 index 0000000..b8699af Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Regular-dEFHw1tF.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 b/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 new file mode 100644 index 0000000..95c48b1 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-SemiBold-PyS8DO2L.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 b/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 new file mode 100644 index 0000000..ddfe19e Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 b/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 new file mode 100644 index 0000000..0790960 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-Thin-eKObIkJC.woff2 differ diff --git a/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 b/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 new file mode 100644 index 0000000..a7bf213 Binary files /dev/null and b/py/iopaint/web_app/assets/Inter-ThinItalic-L6uBn3RP.woff2 differ diff --git a/py/iopaint/web_app/assets/index-8BlaS7ws.js b/py/iopaint/web_app/assets/index-8BlaS7ws.js new file mode 100644 index 0000000..8ae5b4c --- /dev/null +++ b/py/iopaint/web_app/assets/index-8BlaS7ws.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(e,2,!1,e,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(e){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={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"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("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"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("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"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("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"}]]),sV=Kt("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"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};MJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,OJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends Qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>{if(n)return Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}},[n]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-CXO-mkQB.js b/py/iopaint/web_app/assets/index-CXO-mkQB.js new file mode 100644 index 0000000..ef6cf80 --- /dev/null +++ b/py/iopaint/web_app/assets/index-CXO-mkQB.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(e,2,!1,e,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(e){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Oj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Mj;Jt.isAxiosError=Nj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Dj;Jt.default=Jt;const Ij=Jt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,mte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>iU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,gte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[vte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,yte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={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"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Kt("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"}]]),ZU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Kt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Kt("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"}]]),tV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),rV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),iV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),sV=Kt("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"}]]),aV=Kt("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"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),lV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function cV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(uV(mV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=dV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function uV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function dV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!fV(n,{upTo:t}))return n}function fV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function pV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&pV(e)&&t&&e.select()}}const YC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function mV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return OV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},DV=tP(),IV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(vV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(yV,": ").concat(l,`px; + } +`)},LV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return NV(o)},[o]);return f.createElement(DV,{styles:IV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,FV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!FV(e)&&n[t]==="visible")},jV=function(e){return nP(e,"overflowY")},zV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},BV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},UV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?jV(t):zV(t)},oP=function(e,t){return e==="v"?BV(t):UV(t)},VV=function(e,t){return e==="h"&&t==="rtl"?-1:1},WV=function(e,t,n,r,o){var i=VV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},HV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},KV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},YV=0,Qa=[];function GV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(YV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=gV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return WV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&HV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:KV(o)}):null,y?f.createElement(LV,{gapMode:"margin"}):null)}const XV=CV(eP,GV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:XV}))});iP.classNames=Ym.classNames;const Gm=iP;var ZV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},qV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},QV=function(e,t,n,r){var o=qV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||ZV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),QV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[JV,bo]=lP(aP),eW=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(JV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},tW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(tW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[nW,fP]=lP(dP,{forceMount:void 0}),rW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(nW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",oW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(iW,Y({},o,{ref:t}))):null}),iW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",sW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(aW,Y({},o,{ref:t})):f.createElement(lW,Y({},o,{ref:t})))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),lW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",cW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),uW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),dW="DialogClose",fW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(dW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const pW="DialogTitleWarning",[hW,wte]=pB(pW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=eW,gP=uP,Ex=rW,Nd=oW,Dd=sW,Id=cW,Ld=mP,Cx=fW,Zm=Sx,$x=gP,mW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(mW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const gW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));gW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var EW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?wW(d):!d},CW=f.createContext(void 0),$W=function(){return f.useContext(CW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var kW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return f.useContext(kW)};function TW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},PW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function AW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=TW(s),g=RW(),y=g.enabledScopes,x=$W();return PW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(_W(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(EW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(xW(k,F,m==null?void 0:m.preventDefault),!bW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return AW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const OW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>OW()?"Cmd":"Ctrl";function MW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,xte]=An(EP,[Ns]),Tx=Ns(),[NW,bc]=CP(EP),DW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(NW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},IW="PopoverTrigger",LW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(IW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[FW,jW]=CP($P,{forceMount:void 0}),zW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(FW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",BW=f.forwardRef((e,t)=>{const n=jW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(UW,Y({},o,{ref:t})):f.createElement(VW,Y({},o,{ref:t})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),VW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const WW=DW,HW=LW,KW=zW,TP=BW,YW=WW,GW=HW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(KW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function XW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var ZW=function(e,t){var n=XW();f.useEffect(function(){if(!n)return e()},t)};const qW=ZW;var QW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var xH=Lh.exports;const bH=lm(xH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function _H(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function TH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=RH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function PH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=kH({photos:e,containerWidth:o,targetRowHeight:i}),u=TH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=$H(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function AH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function OH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:AH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...OH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function NH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(NH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function IH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function FH(e,t,n,r){return LH(IH(e,t,n,r),t,r)}function jH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function zH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=jH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=FH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=zH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function BH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function UH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function VH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:VH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??UH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=BH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function HH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function KH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function YH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??KH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function XH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function qH(e,t){const[{containerWidth:n},r]=f.useReducer(XH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:ZH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const QH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function JH(e,t){const n=QH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?JH(n,t):o,r))}function eK({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function tK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function nK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(DH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(HH,{layoutOptions:n,renderColumnContainer:l,...u})}function rK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=qH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?eK({containerWidth:l,...e}):void 0,d=tK(e,l,u);return f.createElement(YH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&nK(e,d,u))}function oK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const iK=f.forwardRef(oK),sK=iK;function aK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const lK=f.forwardRef(aK),cK=lK;function uK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const dK=f.forwardRef(uK),fK=dK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const pK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-pK?"-0":t}function mK(e){return e==null?"":hK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function gK(e){return e===!0||e===!1||vK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function vK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const yK="Incorrect 'index' type",wK=e=>`Invalid value for key ${e}`,xK=e=>`Pattern length exceeds max of ${e}.`,bK=e=>`Missing ${e} property in key`,_K=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(bK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(_K(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function EK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||gK(d)))n.push(mK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function AK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function OK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(xK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=OK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function NK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:NK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=MK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class DK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class zK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[DK,KP,LK,FK,zK,jK,IK,HP],u2=m1.length,BK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,UK="|";function VK(e,t={}){return e.split(UK).map(n=>{let r=n.trim().split(BK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),YK=e=>!!e[y1.PATH],GK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=YK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(GK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(wK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function XK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function ZK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function qK(e,t){t.score=e.score}function QK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(ZK),r&&o.push(qK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(yK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),QK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=AK;_c.config=He;_c.parseQuery=YP;KK(HK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const JK=f.createContext(void 0);function Sc(e){const t=f.useContext(JK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",eY={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,tY]=zd(Dx),[nY,Qm]=An(Dx,[tY]),[rY,oY]=nY(Dx),iY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(sY,Y({},e,{ref:t}))))),sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(rY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,eY);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),aY="RovingFocusGroupItem",lY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=oY(aY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=dY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?fY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),cY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function uY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function dY(e,t,n){const r=uY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return cY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function fY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=iY,qP=lY,QP="Tabs",[pY,bte]=An(QP,[Qm]),JP=Qm(),[hY,Ix]=pY(QP),mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(hY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),gY="TabsList",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(gY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),yY="TabsTrigger",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(yY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),xY="TabsContent",bY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(xY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const _Y=mY,n5=vY,r5=wY,o5=bY,i5=_Y,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SY=[" ","Enter","ArrowUp","ArrowDown"],EY=[" ","Enter"],Jm="Select",[eg,tg,CY]=zd(Jm),[Ec,_te]=An(Jm,[CY,Ns]),jx=Ns(),[$Y,Oa]=Ec(Jm),[kY,RY]=Ec(Jm),TY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement($Y,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(kY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},PY="SelectTrigger",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(PY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&SY.includes(x.key)&&(y(),x.preventDefault())})})))}),OY="SelectValue",MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(OY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),NY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),DY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",IY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(LY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:FY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(jY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[jY,zx]=Ec(ic,{}),p2="SelectViewport",zY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),BY="SelectGroup",[UY,VY]=Ec(BY),WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(UY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),HY="SelectLabel",KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=VY(HY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[YY,a5]=Ec(b1),GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(YY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(EY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=RY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),ZY="SelectItemIndicator",qY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(ZY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",QY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",JY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),eG=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=tG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function tG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const nG=TY,p5=AY,rG=MY,oG=NY,iG=DY,h5=IY,sG=zY,aG=WY,m5=KY,g5=GY,lG=XY,cG=qY,v5=QY,y5=JY,w5=eG,aa=nG,wl=aG,la=rG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(oG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(iG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(sG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));uG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(lG,{children:t})]}));us.displayName=g5.displayName;const dG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));dG.displayName=w5.displayName;function fG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,Ste]=An(_5),[pG,qr]=S5(_5),hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(pG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),mG="ScrollAreaViewport",gG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(mG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(yG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),yG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=fG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return $G(g,s.current,l,y)}return n==="horizontal"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(xG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),xG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[bG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(bG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",_G=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(SG,Y({ref:t},r)))}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=kG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",EG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(CG,Y({},e,{ref:t})):null}),CG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function $G(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=hG,RG=gG,TG=EG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(TG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(_G,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",PG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function AG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=cV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=bH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:PG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(sK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(cK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(rK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,OG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(OG(t)),MG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),NG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function DG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function IG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const FG=e=>e.render(LG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var jG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function zG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",UG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var VG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,WG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var HG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,KG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const YG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GG(e={},t){let n={...YG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),KG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,VG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?jG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!WG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||HG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=UG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function XG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},ZG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(QG(t.names||Object.keys(e),r)){var s=Object.assign({},qG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},qG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},QG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},JG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},eX=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:ZG(JG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let tX=Kh;function S1(){return tX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),nX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const rX=/^c[^\s-]{8,}$/i,oX=/^[a-z][a-z0-9]*$/,iX=/^[0-9A-HJKMNP-TV-Z]{26}$/,sX=/^[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,aX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const cX=/^(((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}))$/,uX=/^(([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})))$/,dX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function fX(e,t){return!!((t==="v4"||!t)&&cX.test(e)||(t==="v6"||!t)&&uX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function pX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?pX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),nX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const mX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",gX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(vX(o,n)):null}};function vX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return gX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const yX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=yX,wX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(wX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const xX=NG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(FG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const bX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});bX.displayName="FormMessage";const a3="Switch",[_X,Ete]=An(a3),[SX,EX]=_X(a3),CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(SX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),$X="SwitchThumb",kX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=EX($X,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=CX,TX=kX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(TX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const PX="AlertDialog",[AX,Cte]=An(PX,[cP]),Is=cP(),OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},NX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[DX,IX]=AX(u3),LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(hW,{contentName:u3,titleName:FX,docsSlug:"alert-dialog"},f.createElement(DX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),FX="AlertDialogTitle",jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),UX="AlertDialogCancel",VX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=IX(UX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),WX=OX,HX=MX,d3=NX,f3=LX,p3=BX,h3=VX,m3=jX,g3=zX,KX=WX,YX=HX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(YX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=m3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));XX.displayName=g3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));ZX.displayName=p3.displayName;const qX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));qX.displayName=h3.displayName;const QX=mX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",JX=[I1,x3];function eZ(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=XG({resolver:eX(QX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(KX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(aV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:JX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(xX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const tZ="/assets/kofi_button_black-XI_Dr2zg.png";function nZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:tZ,className:"h-[32px]"})})})]})]})}const rZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(AG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(YW,{open:S,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(sV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(wH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(nZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(eZ,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},oZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},iZ=function(e){return-Math.cos(e*Math.PI)/2+.5},sZ=function(e){return e},aZ=function(e){return e*e},lZ=function(e){return e*(2-e)},cZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},uZ=function(e){return e*e*e},dZ=function(e){return--e*e*e+1},fZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},pZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},mZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},gZ=function(e){return e*e*e*e*e},vZ=function(e){return 1+--e*e*e*e*e},yZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:iZ,linear:sZ,easeInQuad:aZ,easeOutQuad:lZ,easeInOutQuad:cZ,easeInCubic:uZ,easeOutCubic:dZ,easeInOutCubic:fZ,easeInQuart:pZ,easeOutQuart:hZ,easeInOutQuart:mZ,easeInQuint:gZ,easeOutQuint:vZ,easeInOutQuint:yZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function wZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=wZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function xZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var bZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=xZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=bZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},_Z=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function EZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function CZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var $Z=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},kZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function TZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function PZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function AZ(e,t){var n=kZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=PZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function OZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=TZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):_Z(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?OZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},ZZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},qZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},QZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},JZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},eq=160,tq=100,nq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},rq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=YZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=GZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},oq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},tq);var i=XZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},eq))},iq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},sq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=QZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=JZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},aq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},lq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function cq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return lq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var uq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},dq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=HZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(nq(n,r),rq(n,r),oq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=ZZ(n,r);u&&(iq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=qZ(n);u&&(r.preventDefault(),r.stopPropagation(),sq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(aq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=uq(n,r);i&&cq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):VZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),fq=function(e,t){return typeof e=="function"?e(t):e},pq=Fe.forwardRef(function(e,t){var n=f.useRef(new dq(e)).current,r=fq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:WZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var mq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(mq);var gq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,vq,yq]=zd(Wd),[L3,$te]=An(Wd,[yq]),[wq,dg]=L3(Wd),xq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?bq:_q,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Aq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Dq(i),K=Iq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Tq(W,Q,te);if(Nq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(wq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(Rq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),_q=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(Sq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",$q=f.forwardRef((e,t)=>{const n=vq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(kq,Y({},e,{ref:i,index:s}))}),kq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Pq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Oq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Tq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Pq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Aq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Oq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Nq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Dq(e){return(String(e).split(".")[1]||"").length}function Iq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=xq,Lq=Eq,Fq=Cq,jq=$q,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Lq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Fq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(jq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},zq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},Bq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${zq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Uq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Vq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Wq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Vq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Hq=()=>v.jsx("div",{children:v.jsx(Uq,{})}),nl={capture:!0,passive:!1},Kq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Kq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Gq=200,Xq=10,Zq=200,lu=300;function qq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Gq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(fK,{})}),Sg=()=>v.jsx(pq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(gq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(Bq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Yq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Wq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Xq,max:Zq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(lV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(iV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Jq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],eQ=[...Jq,...V3],tQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},nQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,rQ,oQ]=zd(fg),[Na,W3]=An(fg,[oQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[iQ,Hd]=Na(fg),sQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(iQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[aQ,X3]=Na(G3,{forceMount:void 0}),lQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(aQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[cQ,Jx]=Na(yo),uQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(dQ,Y({},o,{ref:t})):f.createElement(fQ,Y({},o,{ref:t})))))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),fQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=rQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=TQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&AQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(cQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!eQ.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),kQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),pQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),mQ="MenuRadioGroup",[kte,gQ]=Na(mQ,{value:void 0,onValueChange:()=>{}}),vQ="MenuRadioItem",yQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=gQ(vQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,wQ]=Na(q3,{checked:!1}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=wQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),bQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[_Q,eA]=Na(J3),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(_Q,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",EQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&tQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),CQ="MenuSubContent",$Q=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(CQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=nQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function kQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function TQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function PQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function AQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return PQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const OQ=sQ,MQ=Y3,NQ=lQ,DQ=uQ,IQ=pQ,LQ=tb,FQ=hQ,jQ=yQ,zQ=xQ,BQ=bQ,UQ=SQ,VQ=EQ,WQ=$Q,nA="DropdownMenu",[HQ,Rte]=An(nA,[W3]),Sr=W3(),[KQ,rA]=HQ(nA),YQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(KQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(OQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",XQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(GQ,n),s=Sr(n);return f.createElement(MQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),ZQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(NQ,Y({},r,n))},qQ="DropdownMenuContent",QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(qQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(DQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(UQ,Y({},s,{open:l,onOpenChange:u}),n)},sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t}))}),aJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(WQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),lJ=YQ,cJ=XQ,uJ=ZQ,oA=QQ,iA=JQ,sA=eJ,aA=tJ,lA=nJ,cA=rJ,uA=oJ,dJ=iJ,dA=sJ,fA=aJ,fJ=lJ,pJ=cJ,K2=dJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(uJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const hJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=aA.displayName;const mJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));mJ.displayName=lA.displayName;const gJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));gJ.displayName=iA.displayName;const vJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));vJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},yJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(fJ,{modal:!1,children:[v.jsx(pJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},wJ=Sx,xJ=gP,bJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const _J=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(bJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(_J({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Id.displayName;const EJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));EJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},$J=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(oV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(nV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},kJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(CJ,{}):e.model.name===iC?v.jsx(kJ,{}):v.jsx($J,{});return v.jsxs(wJ,{open:n,modal:!1,children:[v.jsx(xJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function TJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},AJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:OJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},OJ=(e,t)=>{if(AJ){const n=PJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},NJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return LJ(e)}function LJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const FJ=Br.setTimeout,jJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=FJ.bind(Br),e.clearTimeoutFn=jJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const zJ=1.33;function BJ(e){return typeof e=="string"?UJ(e):Math.ceil((e.byteLength||e.size)*zJ)}function UJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function VJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function WJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};NJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends Qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,qJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class QJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class JJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=IJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=DJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const eee={websocket:QJ,webtransport:JJ,polling:ZJ},tee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,nee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=tee.exec(e||""),i={},s=14;for(;s--;)i[nee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=ree(i,i.path),i.queryKey=oee(i,i.query),i}function ree(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function oee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=qJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=WJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new eee[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,lee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",cee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return see&&(e instanceof ArrayBuffer||aee(e))||lee&&e instanceof Blob||cee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||gee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=iee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[yee,Tte]=An(OA),[wee,xee]=yee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(wee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(Eee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Cee(o,n)):null}};const bee="ProgressIndicator",_ee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=xee(bee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function Eee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Cee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,$ee=_ee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx($ee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const kee="",Vi=rh(kee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Tee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(yJ,{}),v.jsx(Qq,{})]}),v.jsx(Hq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(qq,{file:e}):v.jsx(v.Fragment,{})]})},Pee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Aee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Pee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Oee,Mee]=zd("Toast"),[jA,Pte]=An("Toast",[Mee]),[Nee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Nee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Dee="ToastViewport",Iee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Lee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Iee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Dee,n),l=Oee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Jee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Fee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Fee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",jee="toast.swipeStart",zee="toast.swipeMove",Bee="toast.swipeCancel",Uee="toast.swipeEnd",Vee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Wee,Hee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Kee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Wee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(zee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(jee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Uee,y,K,{discrete:!0}):_p(Bee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Kee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return qee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Xee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Xee}\``)}};const Zee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Hee(Zee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function qee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Qee(e){return e.nodeType===e.ELEMENT_NODE}function Jee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const ete=zA,KA=Lee,YA=Vee,GA=Yee,XA=Gee,ZA=UA,qA=VA,tte=ete,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const nte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(nte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const rte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));rte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function ote(){const{toasts:e}=Td();return v.jsxs(tte,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ite=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ste(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=yH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ite.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(ote,{}),v.jsx(rZ,{}),v.jsx(Tee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Aee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ate=typeof window>"u",rO=f.createContext(void 0),lte=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(ute,e),cte=["light","dark"],ute=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=cte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?fte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(dte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},dte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ate)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},fte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),pte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:pte,children:v.jsx(lte,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ste,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-NQyCh9rO.js b/py/iopaint/web_app/assets/index-NQyCh9rO.js new file mode 100644 index 0000000..b7e3c1d --- /dev/null +++ b/py/iopaint/web_app/assets/index-NQyCh9rO.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var xn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xn[e]=new Un(e,2,!1,e,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(e){xn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});xn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=xn.hasOwnProperty(t)?xn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:Cn,useContext:Cn,useEffect:Cn,useImperativeHandle:Cn,useInsertionEffect:Cn,useLayoutEffect:Cn,useMemo:Cn,useReducer:Cn,useRef:Cn,useState:Cn,useDebugValue:Cn,useDeferredValue:Cn,useTransition:Cn,useMutableSource:Cn,useSyncExternalStore:Cn,useId:Cn,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return $n(t),null}else 2*Xt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):($n(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&($n(t),t.subtreeFlags&6&&(t.flags|=8192)):$n(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,Rn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:Rn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Rn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!Rn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(Rn=(r=Rn)||n.memoizedState!==null,ji(e,t,n),Rn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,kn,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,kn,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,kn,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,kn,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(d=>{const h=d;return z(this,kn)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,kn=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,kn).isStale||!My(this.options.staleTime))return;const n=PR(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Qt=mT(rx);Qt.Axios=zp;Qt.CanceledError=Rd;Qt.CancelToken=Oj;Qt.isCancel=dT;Qt.VERSION=hT;Qt.toFormData=Tm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Mj;Qt.isAxiosError=Nj;Qt.mergeConfig=Jl;Qt.AxiosHeaders=pi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=pT.getAdapter;Qt.HttpStatusCode=Dj;Qt.default=Qt;const Ij=Qt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,pte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Kt=>V(Kt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>iU(...Kt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Kt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const bn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};bn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,hte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[mte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(bn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,gte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),yn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});yn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(yn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={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"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Jt("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"}]]),ZU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Jt("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"}]]),tV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),oV=Jt("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"}]]),iV=Jt("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"}]]),VC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),sV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function aV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(lV(pV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=cV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function lV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function cV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!uV(n,{upTo:t}))return n}function uV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function dV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&dV(e)&&t&&e.select()}}const YC=fV();function fV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return PV;var t=AV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},MV=tP(),NV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(mV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(gV,": ").concat(l,`px; + } +`)},DV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return OV(o)},[o]);return f.createElement(MV,{styles:NV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,IV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!IV(e)&&n[t]==="visible")},LV=function(e){return nP(e,"overflowY")},FV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},jV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},zV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?LV(t):FV(t)},oP=function(e,t){return e==="v"?jV(t):zV(t)},BV=function(e,t){return e==="h"&&t==="rtl"?-1:1},UV=function(e,t,n,r,o){var i=BV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},VV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},WV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},HV=0,Qa=[];function KV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(HV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=hV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return UV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&VV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:WV(o)}):null,y?f.createElement(DV,{gapMode:"margin"}):null)}const YV=SV(eP,KV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:YV}))});iP.classNames=Ym.classNames;const Gm=iP;var GV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},XV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},ZV=function(e,t,n,r){var o=XV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||GV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),ZV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[qV,bo]=lP(aP),QV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(qV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},JV="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(JV,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[eW,fP]=lP(dP,{forceMount:void 0}),tW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(eW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",nW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(bn,{present:r||i.open},f.createElement(rW,Y({},o,{ref:t}))):null}),rW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",oW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(iW,Y({},o,{ref:t})):f.createElement(sW,Y({},o,{ref:t})))}),iW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",aW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),lW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(lW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),cW="DialogClose",uW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const dW="DialogTitleWarning",[fW,vte]=pB(dW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=QV,gP=uP,Ex=tW,Nd=nW,Dd=oW,Id=aW,Ld=mP,Cx=uW,Zm=Sx,$x=gP,pW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const hW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));hW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?vW(d):!d},SW=f.createContext(void 0),EW=function(){return f.useContext(SW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var CW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),$W=function(){return f.useContext(CW)};function kW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},RW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function TW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=kW(s),g=$W(),y=g.enabledScopes,x=EW();return RW(function(){if(!((m==null?void 0:m.enabled)===!1||!bW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(xW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(_W(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(yW(k,F,m==null?void 0:m.preventDefault),!wW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return TW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const PW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>PW()?"Cmd":"Ctrl";function AW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,yte]=An(EP,[Ns]),Tx=Ns(),[OW,bc]=CP(EP),MW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},NW="PopoverTrigger",DW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(NW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[IW,LW]=CP($P,{forceMount:void 0}),FW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(IW,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",jW=f.forwardRef((e,t)=>{const n=LW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(zW,Y({},o,{ref:t})):f.createElement(BW,Y({},o,{ref:t})))}),zW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const UW=MW,VW=DW,WW=FW,TP=jW,HW=UW,KW=VW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(WW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function YW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var GW=function(e,t){var n=YW();f.useEffect(function(){if(!n)return e()},t)};const XW=GW;var ZW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(yn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[_n]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Kt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Kt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=En(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=Sn(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=En(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Gt){var no=w,ri=$;return w=$=n,ne=Gt,N=a.apply(ri,no),N}function Ie(Gt){return ne=Gt,D=Hc(nt,c),re?Re(Gt):N}function Qe(Gt){var no=Gt-B,ri=Gt-ne,IS=c-no;return se?Sn(IS,T-ri):IS}function Le(Gt){var no=Gt-B,ri=Gt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Gt=Of();if(Le(Gt))return at(Gt);D=Hc(nt,Qe(Gt))}function at(Gt){return D=n,me&&w?Re(Gt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Gt=Of(),no=Le(Gt);if(w=arguments,$=this,B=Gt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=Sn(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Yt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=En(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&En(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=En(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return Sn(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=Sn(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var yH=Lh.exports;const wH=lm(yH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function xH(e){return(t,n)=>e(n)-e(t)}class bH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function $H(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=$H(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function RH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=CH({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=EH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function TH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function PH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:TH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...PH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function AH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(OH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function NH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function IH(e,t,n,r){return DH(NH(e,t,n,r),t,r)}function LH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function FH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=LH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=IH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=FH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function jH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function zH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function BH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:BH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??zH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function UH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function WH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function HH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??WH)({containerProps:u,containerRef:o,layout:t,children:r}))}function KH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function XH(e,t){const[{containerWidth:n},r]=f.useReducer(YH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:GH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const ZH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function qH(e,t){const n=ZH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?qH(n,t):o,r))}function QH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function JH(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function eK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(MH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(UH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u})}function tK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=XH(KH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?QH({containerWidth:l,...e}):void 0,d=JH(e,l,u);return f.createElement(HH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&eK(e,d,u))}function nK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const rK=f.forwardRef(nK),oK=rK;function iK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const sK=f.forwardRef(iK),aK=sK;function lK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const cK=f.forwardRef(lK),uK=cK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const dK=1/0;function fK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-dK?"-0":t}function pK(e){return e==null?"":fK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function hK(e){return e===!0||e===!1||mK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function mK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const gK="Incorrect 'index' type",vK=e=>`Invalid value for key ${e}`,yK=e=>`Pattern length exceeds max of ${e}.`,wK=e=>`Missing ${e} property in key`,xK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class bK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(wK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(xK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||hK(d)))n.push(pK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function TK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function PK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function AK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(yK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=PK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=AK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class MK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class NK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[MK,KP,DK,IK,FK,LK,NK,HP],u2=m1.length,jK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,zK="|";function BK(e,t={}){return e.split(zK).map(n=>{let r=n.trim().split(jK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),HK=e=>!!e[y1.PATH],KK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=HK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(KK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(vK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function GK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function XK(e,t){t.score=e.score}function ZK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(GK),r&&o.push(XK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new bK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(gK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),ZK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=TK;_c.config=He;_c.parseQuery=YP;WK(VK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const qK=f.createContext(void 0);function Sc(e){const t=f.useContext(qK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",QK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,JK]=zd(Dx),[eY,Qm]=An(Dx,[JK]),[tY,nY]=eY(Dx),rY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(oY,Y({},e,{ref:t}))))),oY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(tY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,QK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),iY="RovingFocusGroupItem",sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=nY(iY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=cY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?uY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),aY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cY(e,t,n){const r=lY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return aY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function uY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=rY,qP=sY,QP="Tabs",[dY,wte]=An(QP,[Qm]),JP=Qm(),[fY,Ix]=dY(QP),pY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(fY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),hY="TabsList",mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(hY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),gY="TabsTrigger",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(gY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),yY="TabsContent",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(yY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(bn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const xY=pY,n5=mY,r5=vY,o5=wY,i5=xY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const bY=[" ","Enter","ArrowUp","ArrowDown"],_Y=[" ","Enter"],Jm="Select",[eg,tg,SY]=zd(Jm),[Ec,xte]=An(Jm,[SY,Ns]),jx=Ns(),[EY,Oa]=Ec(Jm),[CY,$Y]=Ec(Jm),kY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(EY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(CY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},RY="SelectTrigger",TY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(RY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&bY.includes(x.key)&&(y(),x.preventDefault())})})))}),PY="SelectValue",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(PY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),MY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",NY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(DY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),DY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:IY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(LY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[LY,zx]=Ec(ic,{}),p2="SelectViewport",FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),jY="SelectGroup",[zY,BY]=Ec(jY),UY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(zY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),VY="SelectLabel",WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=BY(VY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[HY,a5]=Ec(b1),KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(HY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(_Y.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=$Y(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),GY="SelectItemIndicator",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(GY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",ZY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",qY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),QY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=JY(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function JY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const eG=kY,p5=TY,tG=AY,nG=OY,rG=MY,h5=NY,oG=FY,iG=UY,m5=WY,g5=KY,sG=YY,aG=XY,v5=ZY,y5=qY,w5=QY,aa=eG,wl=iG,la=tG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(nG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(rG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(oG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const lG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));lG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(aG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(sG,{children:t})]}));us.displayName=g5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));cG.displayName=w5.displayName;function uG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,bte]=An(_5),[dG,qr]=S5(_5),fG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(dG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),pG="ScrollAreaViewport",hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(mG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),mG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(bn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=uG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(bn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return EG(g,s.current,l,y)}return n==="horizontal"?f.createElement(vG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),vG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[wG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(wG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",xG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(bn,{present:n||o.hasThumb},f.createElement(bG,Y({ref:t},r)))}),bG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=CG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",_G=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(SG,Y({},e,{ref:t})):null}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function EG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=fG,$G=hG,kG=_G,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx($G,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(kG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(xG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",RG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function TG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=aV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=wH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:RG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(oK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(aK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(tK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,PG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(PG(t)),AG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!AG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),OG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function MG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function NG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const IG=e=>e.render(DG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var LG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function FG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",zG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var BG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,UG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var VG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,WG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const HG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function KG(e={},t){let n={...HG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),WG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,BG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?LG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const _n=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!UG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||VG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,_n),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,_n,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(_n),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(_n),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=zG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Kt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Kt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function YG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...KG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},GG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(ZG(t.names||Object.keys(e),r)){var s=Object.assign({},XG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},XG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},ZG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},qG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},QG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:GG(qG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let JG=Kh;function S1(){return JG}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),eX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new fX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tX=/^c[^\s-]{8,}$/i,nX=/^[a-z][a-z0-9]*$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^[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,iX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const aX=/^(((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}))$/,lX=/^(([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})))$/,cX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function uX(e,t){return!!((t==="v4"||!t)&&aX.test(e)||(t==="v6"||!t)&&lX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function dX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?dX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class fX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),eX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const pX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",hX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(mX(o,n)):null}};function mX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return hX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const gX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=gX,vX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(vX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const yX=OG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(IG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const wX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});wX.displayName="FormMessage";const a3="Switch",[xX,_te]=An(a3),[bX,_X]=xX(a3),SX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(bX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement($X,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),EX="SwitchThumb",CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(EX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),$X=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=SX,kX=CX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const RX="AlertDialog",[TX,Ste]=An(RX,[cP]),Is=cP(),PX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},OX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[MX,NX]=TX(u3),DX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(fW,{contentName:u3,titleName:IX,docsSlug:"alert-dialog"},f.createElement(MX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),IX="AlertDialogTitle",LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),zX="AlertDialogCancel",BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=NX(zX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),UX=PX,VX=AX,d3=OX,f3=DX,p3=jX,h3=BX,m3=LX,g3=FX,WX=UX,HX=VX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(HX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const KX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));KX.displayName=m3.displayName;const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=g3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));GX.displayName=p3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));XX.displayName=h3.displayName;const ZX=pX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",qX=[I1,x3];function QX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=YG({resolver:QG(ZX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(WX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(iV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:qX.map(O=>v.jsx(yn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(yX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(yn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const JX="/assets/kofi_button_black-XI_Dr2zg.png";function eZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:JX,className:"h-[32px]"})})})]})]})}const tZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(TG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(HW,{open:S,children:[v.jsx(KW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(oV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(vH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(eZ,{}),v.jsx(AW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(QX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},nZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},rZ=function(e){return-Math.cos(e*Math.PI)/2+.5},oZ=function(e){return e},iZ=function(e){return e*e},sZ=function(e){return e*(2-e)},aZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},lZ=function(e){return e*e*e},cZ=function(e){return--e*e*e+1},uZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},dZ=function(e){return e*e*e*e},fZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},hZ=function(e){return e*e*e*e*e},mZ=function(e){return 1+--e*e*e*e*e},gZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:rZ,linear:oZ,easeInQuad:iZ,easeOutQuad:sZ,easeInOutQuad:aZ,easeInCubic:lZ,easeOutCubic:cZ,easeInOutCubic:uZ,easeInQuart:dZ,easeOutQuart:fZ,easeInOutQuart:pZ,easeInQuint:hZ,easeOutQuint:mZ,easeInOutQuint:gZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function vZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=vZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function yZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var wZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=yZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=wZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},xZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},bZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function SZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var EZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},CZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},$Z=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function RZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function TZ(e,t){var n=CZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=RZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function PZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=$Z(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=kZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?bZ(e,t):xZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?PZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},GZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},XZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},ZZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},qZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},QZ=160,JZ=100,eq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},tq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=HZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=KZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},nq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},JZ);var i=YZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},QZ))},rq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},oq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=ZZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=qZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},iq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},sq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function aq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return sq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var lq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},cq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=VZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(eq(n,r),tq(n,r),nq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(AZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=GZ(n,r);u&&(rq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=XZ(n);u&&(r.preventDefault(),r.stopPropagation(),oq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(iq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=lq(n,r);i&&aq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):BZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),uq=function(e,t){return typeof e=="function"?e(t):e},dq=Fe.forwardRef(function(e,t){var n=f.useRef(new cq(e)).current,r=uq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:UZ([n,t])}))});function fq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};fq(pq);var hq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,mq,gq]=zd(Wd),[L3,Ete]=An(Wd,[gq]),[vq,dg]=L3(Wd),yq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?wq:xq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Tq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Mq(i),K=Nq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=kq(W,Q,te);if(Oq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(vq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement($q,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),wq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),bq="SliderTrack",_q=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(bq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Eq=f.forwardRef((e,t)=>{const n=mq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(Cq,Y({},e,{ref:i,index:s}))}),Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Rq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Pq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),$q=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Rq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Tq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Pq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Aq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Aq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mq(e){return(String(e).split(".")[1]||"").length}function Nq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=yq,Dq=_q,Iq=Sq,Lq=Eq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Dq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Iq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Lq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},Fq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},jq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${Fq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},zq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(yn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(yn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Bq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Uq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Bq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Vq=()=>v.jsx("div",{children:v.jsx(zq,{})}),nl={capture:!0,passive:!1},Wq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Wq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Kq=200,Yq=10,Gq=200,lu=300;function Xq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Kt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),_n=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Kq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(cC(H)){je(!1);return}!_n()||g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(uK,{})}),Sg=()=>v.jsx(dq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(hq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(jq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Hq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Uq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Gq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Kt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(sV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(rV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Zq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Qq=[...qq,...V3],Jq={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},eQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,tQ,nQ]=zd(fg),[Na,W3]=An(fg,[nQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[rQ,Hd]=Na(fg),oQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(rQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[iQ,X3]=Na(G3,{forceMount:void 0}),sQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(iQ,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[aQ,Jx]=Na(yo),lQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(cQ,Y({},o,{ref:t})):f.createElement(uQ,Y({},o,{ref:t})))))}),cQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=tQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=kQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&TQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(aQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Qq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),CQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),dQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),fQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[Cte,hQ]=Na(pQ,{value:void 0,onValueChange:()=>{}}),mQ="MenuRadioItem",gQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=hQ(mQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,vQ]=Na(q3,{checked:!1}),yQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=vQ(q3,n);return f.createElement(bn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[xQ,eA]=Na(J3),bQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(xQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",_Q=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&Jq[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),SQ="MenuSubContent",EQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(SQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=eQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function CQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function $Q(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=$Q(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function RQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function TQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return RQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const PQ=oQ,AQ=Y3,OQ=sQ,MQ=lQ,NQ=dQ,DQ=tb,IQ=fQ,LQ=gQ,FQ=yQ,jQ=wQ,zQ=bQ,BQ=_Q,UQ=EQ,nA="DropdownMenu",[VQ,$te]=An(nA,[W3]),Sr=W3(),[WQ,rA]=VQ(nA),HQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(WQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(PQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},KQ="DropdownMenuTrigger",YQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(KQ,n),s=Sr(n);return f.createElement(AQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),GQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(OQ,Y({},r,n))},XQ="DropdownMenuContent",ZQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(XQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(MQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(NQ,Y({},o,r,{ref:t}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(zQ,Y({},s,{open:l,onOpenChange:u}),n)},oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),sJ=HQ,aJ=YQ,lJ=GQ,oA=ZQ,iA=qQ,sA=QQ,aA=JQ,lA=eJ,cA=tJ,uA=nJ,cJ=rJ,dA=oJ,fA=iJ,uJ=sJ,dJ=aJ,K2=cJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(lJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const fJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));fJ.displayName=aA.displayName;const pJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=lA.displayName;const hJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));hJ.displayName=iA.displayName;const mJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));mJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},gJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(uJ,{modal:!1,children:[v.jsx(dJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},vJ=Sx,yJ=gP,wJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const xJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(wJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(xJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const bJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));bJ.displayName=Id.displayName;const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(yn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),SJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(yn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},EJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(yn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(yn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},$J=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(SJ,{}):e.model.name===iC?v.jsx(CJ,{}):v.jsx(EJ,{});return v.jsxs(vJ,{open:n,modal:!1,children:[v.jsx(yJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(yn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function kJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},TJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:PJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},PJ=(e,t)=>{if(TJ){const n=RJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",AJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},OJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function qt(e){if(e)return DJ(e)}function DJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const IJ=Br.setTimeout,LJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=IJ.bind(Br),e.clearTimeoutFn=LJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const FJ=1.33;function jJ(e){return typeof e=="string"?zJ(e):Math.ceil((e.byteLength||e.size)*FJ)}function zJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function BJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function UJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,AJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=KJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,XJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ZJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class qJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=NJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=MJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const QJ={websocket:ZJ,webtransport:qJ,polling:GJ},JJ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,eee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=JJ.exec(e||""),i={},s=14;for(;s--;)i[eee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=tee(i,i.path),i.queryKey=nee(i,i.query),i}function tee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function nee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends qt{constructor(t,n={}){super(),this.binaryType=XJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=UJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new QJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,see=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",aee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return oee&&(e instanceof ArrayBuffer||iee(e))||see&&e instanceof Blob||aee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||hee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=ree(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[gee,kte]=An(OA),[vee,yee]=gee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=bee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(vee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(See(o,n)):null}};const wee="ProgressIndicator",xee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=yee(wee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function bee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function See(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Eee=xee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Eee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const Cee="",Vi=rh(Cee),$ee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(gJ,{}),v.jsx(Zq,{})]}),v.jsx(Vq,{}),v.jsx($ee,{}),v.jsx($J,{}),e?v.jsx(Xq,{file:e}):v.jsx(v.Fragment,{})]})},Ree=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Tee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Ree();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Pee,Aee]=zd("Toast"),[jA,Rte]=An("Toast",[Aee]),[Oee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Mee="ToastViewport",Nee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Dee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Nee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Mee,n),l=Pee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Iee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Iee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Lee="toast.swipeStart",Fee="toast.swipeMove",jee="toast.swipeCancel",zee="toast.swipeEnd",Bee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(bn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Uee,Vee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Wee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Uee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(Fee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Lee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(zee,y,K,{discrete:!0}):_p(jee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Wee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Xee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Hee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Gee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Vee(Gee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Zee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Xee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Zee(e){return e.nodeType===e.ELEMENT_NODE}function qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Qee=zA,KA=Dee,YA=Bee,GA=Hee,XA=Kee,ZA=UA,qA=VA,Jee=Qee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const ete=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(ete({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const tte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));tte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function nte(){const{toasts:e}=Td();return v.jsxs(Jee,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const rte=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ote(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=gH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;rte.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(nte,{}),v.jsx(tZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Tee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ite=typeof window>"u",rO=f.createContext(void 0),ste=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(lte,e),ate=["light","dark"],lte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=ate,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?ute():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(cte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},cte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ite)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},ute=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),dte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:dte,children:v.jsx(ste,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ote,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-QuEBEP4v.js b/py/iopaint/web_app/assets/index-QuEBEP4v.js new file mode 100644 index 0000000..9f09c0b --- /dev/null +++ b/py/iopaint/web_app/assets/index-QuEBEP4v.js @@ -0,0 +1,165 @@ +var Fv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Fv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Fv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Wf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Fv(e,t,"access private method"),n);function $9(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x$={exports:{}},fm={},b$={exports:{}},it={};/** + * @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. + */var kd=Symbol.for("react.element"),R9=Symbol.for("react.portal"),k9=Symbol.for("react.fragment"),T9=Symbol.for("react.strict_mode"),P9=Symbol.for("react.profiler"),A9=Symbol.for("react.provider"),M9=Symbol.for("react.context"),O9=Symbol.for("react.forward_ref"),N9=Symbol.for("react.suspense"),D9=Symbol.for("react.memo"),I9=Symbol.for("react.lazy"),B_=Symbol.iterator;function L9(e){return e===null||typeof e!="object"?null:(e=B_&&e[B_]||e["@@iterator"],typeof e=="function"?e:null)}var S$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_$=Object.assign,E$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}yc.prototype.isReactComponent={};yc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function C$(){}C$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}var rw=nw.prototype=new C$;rw.constructor=nw;_$(rw,yc.prototype);rw.isPureReactComponent=!0;var U_=Array.isArray,$$=Object.prototype.hasOwnProperty,ow={current:null},R$={key:!0,ref:!0,__self:!0,__source:!0};function k$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)$$.call(t,r)&&!R$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],p=1,m=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),m=n(u);m!==null&&(!(m.expirationTime>X)||H&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var pe=le(m.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?m.callback=pe:m===n(u)&&r(u),C(X)}else r(u);m=n(u)}if(m!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{m=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(M$);A$.exports=M$;var X9=A$.exports;/** + * @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. + */var O$=d,yr=X9;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),H0=Object.prototype.hasOwnProperty,Z9=/^[: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]*$/,W_={},H_={};function q9(e){return H0.call(H_,e)?!0:H0.call(W_,e)?!1:Z9.test(e)?H_[e]=!0:(W_[e]=!0,!1)}function Q9(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function J9(e,t,n,r){if(t===null||typeof t>"u"||Q9(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(e,2,!1,e,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(e){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(e){return e[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(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Bv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function eD(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Uv(e.type,!1),e;case 11:return e=Uv(e.type.render,!1),e;case 1:return e=Uv(e.type,!0),e;default:return""}}function X0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case pl:return"Portal";case K0:return"Profiler";case cw:return"StrictMode";case G0:return"Suspense";case Y0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case I$:return(e.displayName||"Context")+".Consumer";case D$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:X0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return X0(e(t))}catch{}}return null}function tD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return X0(t);case 8:return t===cw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function F$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nD(e){var t=F$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Gf(e){e._valueTracker||(e._valueTracker=nD(e))}function j$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=F$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Z0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function G_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function z$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function q0(e,t){z$(e,t);var n=Rs(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&Q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Y_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},rD=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){rD.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function W$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function H$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=W$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var oD=zt({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 ty(e,t){if(t){if(oD[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ny(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 ry=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var oy=null,kl=null,Tl=null;function q_(e){if(e=Ad(e)){if(typeof oy!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),oy(e.stateNode,e.type,t))}}function K$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function G$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,q_(e),t)for(e=0;e>>=0,e===0?32:31-(mD(e)/gD|0)|0}var Xf=64,Zf=4194304;function wu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function xD(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=$u),sE=" ",aE=!1;function h5(e,t){switch(e){case"keyup":return YD.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function p5(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function ZD(e,t){switch(e){case"compositionend":return p5(t);case"keypress":return t.which!==32?null:(aE=!0,sE);case"textInput":return e=t.data,e===sE&&aE?null:e;default:return null}}function qD(e,t){if(gl)return e==="compositionend"||!xw&&h5(e,t)?(e=d5(),Mh=vw=us=null,gl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=dE(n)}}function y5(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?y5(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function w5(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sI(e){var t=w5(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&y5(n.ownerDocument.documentElement,n)){if(r!==null&&bw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=fE(n,i);var s=fE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vl=null,uy=null,ku=null,dy=!1;function hE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;dy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(uy,"onSelect"),0xl||(e.current=vy[xl],vy[xl]=null,xl--)}function $t(e,t){xl++,vy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function xE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function k5(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,tD(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function bE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=k5(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,n0=!1;function T5(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,T5(e)}function Ds(){if(!n0&&pi!==null){n0=!0;var e=0,t=bt;try{var n=pi;for(bt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=m(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Kf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&kE(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=zh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=u0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);rh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=c0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=L5(!0),F5=L5(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:ey(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=ey(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function j5(e){fa(Zu.current);var t=fa(Ko.current),n=ey(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var r0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=o0.transition;o0.transition={};try{e(!1),t()}finally{bt=n,o0.transition=r}}function tR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},nR(e))rR(t,n);else if(n=O5(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),oR(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(nR(e))rR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=O5(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),oR(n,t,r))}}function nR(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function rR(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:PE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ih(4194308,4,Z5.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ih(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ih(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:TE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=TE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||U5(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,PE(W5.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,V5.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Io]=t,e[Yu]=r,hR(e,t,!1,!1),t.stateNode=e;e:{switch(s=ny(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var ih=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,Ee=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Ty(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var jE=!1;function NI(e,t){if(fy=fp,e=w5(),bw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,f=0,p=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++p===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(hy={focusedElem:e,selectionRange:n},fp=!1,Ee=t;Ee!==null;)if(t=Ee,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ee=e;else for(;Ee!==null;){t=Ee;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,Ee=e;break}Ee=t.return}return x=jE,jE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Ty(t,n,i)}o=o.next}while(o!==r)}}function bm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Py(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function gR(e){var t=e.alternate;t!==null&&(e.alternate=null,gR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[gy],delete t[gI],delete t[vI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function vR(e){return e.tag===5||e.tag===3||e.tag===4}function zE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||vR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ay(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mp));else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}function My(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(My(e,t,n),e=e.sibling;e!==null;)My(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)yR(e,t,n),n=n.sibling}function yR(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?t0(e.parentNode,n):e.nodeType===1&&t0(e,n),Vu(e)):t0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(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||i&4)&&Ty(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function BE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Ee=e.current;Ee!==null;){var i=Ee,s=i.child;if(Ee.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function $R(e,t){t===0&&(e.mode&1?(t=Zf,Zf<<=1,!(Zf&130023424)&&(Zf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$R(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),$R(e,n)}var RR;RR=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&P5(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Lh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,Sy(t,r,e,n),t=Cy(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Lh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=Ey(null,t,r,e,n);break e;case 1:t=IE(null,t,r,e,n);break e;case 11:t=NE(null,t,r,e,n);break e;case 14:t=DE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ey(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),IE(e,t,r,o,n);case 3:e:{if(uR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,N5(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=LE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=LE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=F5(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return j5(t),e===null&&wy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,py(r,o)?s=null:i!==null&&py(r,i)&&(t.flags|=32),cR(e,t),In(e,t,s,n),t.child;case 6:return e===null&&wy(t),null;case 13:return dR(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var p=f.pending;p===null?u.next=u:(u.next=p.next,p.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),xy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),xy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),DE(e,t,r,o,n);case 15:return aR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Lh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),I5(t,r,o),Sy(t,r,o,n),Cy(null,t,r,!0,e,n);case 19:return fR(e,t,n);case 22:return lR(e,t,n)}throw Error(ce(156,t.tag))};function kR(e,t){return e5(e,t)}function WI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function zh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case K0:return e=Ur(12,n,t,o|2),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(13,n,t,o),e.elementType=G0,e.lanes=i,e;case Y0:return e=Ur(19,n,t,o),e.elementType=Y0,e.lanes=i,e;case L$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D$:s=10;break e;case I$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=L$,e.lanes=n,e.stateNode={isHidden:!1},e}function c0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function u0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Wv(0),this.expirationTimes=Wv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Wv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(MR)}catch(e){console.error(e)}}MR(),P$.exports=br;var Is=P$.exports;const QI=dm(Is);var XE=Is;W0.createRoot=XE.createRoot,W0.hydrateRoot=XE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Ly(e){return typeof e=="number"&&e>=0&&e!==1/0}function OR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ZE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function qE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>jy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function NR(e,t){if(e===t)return e;const n=QE(e)&&QE(t);if(n||jy(e)&&jy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!JE(n)||!n.hasOwnProperty("isPrototypeOf"))}function JE(e){return Object.prototype.toString.call(e)==="[object Object]"}function DR(e){return new Promise(t=>{setTimeout(t,e)})}function eC(e){DR(0).then(e)}function zy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?NR(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,d$,nL=(d$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,d$),Ap=new nL,Ll,os,Fl,f$,rL=(f$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,f$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var IR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function d0(e){return e instanceof IR}function LR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new IR(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},p=()=>{t=!1},m=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!m();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:p}}function iL(){let e=[],t=0,n=p=>{p()},r=p=>{p()};const o=p=>{let m;t++;try{m=p()}finally{t--,t||l()}return m},i=p=>{t?e.push(p):eC(()=>{n(p)})},s=p=>(...m)=>{i(()=>{p(...m)})},l=()=>{const p=e;e=[],p.length&&eC(()=>{r(()=>{p.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:p=>{n=p},setBatchNotifyFunction:p=>{r=p}}}var vn=iL(),va,h$,FR=(h$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ly(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,h$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Bh,ao,di,p$,sL=(p$=class extends FR{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Bh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=zy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!OR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,p,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Bh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Bh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(p=this.options.behavior)==null||p.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;d0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),d0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,LR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Bh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return d0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},p$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,m$,lL=(m$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ZE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ZE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,m$),Oo,yd,dr,Ul,No,qi,g$,cL=(g$=class extends FR{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,LR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((m=(p=this.options).onSuccess)==null?void 0:m.call(p,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},g$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,v$,dL=(v$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Wf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>qE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>qE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,v$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const p=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};p(O);const A=await m(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:tC,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tC(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,y$,pL=(y$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Wf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Wf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,y$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,By,Sd,Uy,_d,Vy,Ed,Wy,Cd,Hy,$d,Ky,Rd,Gy,um,jR,w$,mL=(w$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),nC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Wy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Hy).call(this),tt(this,$d,Ky).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Fy(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Gy).call(this);const i=this.hasListeners();i&&rC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,By).call(this);const s=tt(this,Sd,Uy).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Vy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:p}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=p,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&nC(t,n),B=A&&rC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",p.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof p.data<"u")if(i&&p.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(p.data),E=zy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=p.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=zy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(m=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>f.dataUpdateCount||p.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&p.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&p.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Fy(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const p=f;return j(this,kn)[p]!==n[p]&&u.has(p)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,jR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Wy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Gy).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,By=function(){if(tt(this,Cd,Hy).call(this),oc||j(this,kn).isStale||!Ly(this.options.staleTime))return;const n=OR(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,Uy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Vy=function(t){tt(this,$d,Ky).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Ly(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Wy=function(){tt(this,bd,By).call(this),tt(this,_d,Vy).call(this,tt(this,Sd,Uy).call(this))},Cd=new WeakSet,Hy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Ky=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Gy=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,jR=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},w$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Yy(e,t,t.refetchOnMount)}function Yy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function rC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Fy(e.getCurrentResult(),t)}var zR=d.createContext(void 0),yL=e=>{const t=d.useContext(zR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(zR.Provider,{value:e},t)),BR=d.createContext(!1),xL=()=>d.useContext(BR);BR.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const p=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),p},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function UR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const oC=/^\[(.+)\]$/;function NL(e){if(oC.test(e)){const t=oC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Xy(s,r,i,t)}),r}function Xy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:iC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Xy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Xy(s,iC(t,i),n,r)})})}function iC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const HR="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,p;for(let S=0;Sf?p-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:p}=n(s);let m=r(p?f.substring(0,p):f),g=!!p;if(!m){if(!p)return{isTailwindClass:!1,originalClassName:s};if(m=r(f),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+HR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,p=l+u;return i.has(p)?!1:(i.add(p),o(u,f).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;em(p),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const p=VL(u,n);return o(u,p),p}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const GR=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\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$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function lh(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return GR.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,YR)}function tF(e){return bc(e,"position",YR)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=GR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function YR(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),p=kt("hueRotate"),m=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,lh],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",lh]}],"font-family":[{font:[cu]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,lh]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[p]}],invert:[{invert:[m]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[p]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,lh]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const tx=HL(lF),cF=40,fs="inpaint",ch="diffusers_sd",sC="diffusers_sdxl",uh="diffusers_sd_inpaint",aC="diffusers_sdxl_inpaint",f0="diffusers_other",Uh="#ffcc00bb",lC="ldm",cC="cv2",XR="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function _e(...e){return tx(VR(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function uC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function dC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function fC(e){return e.nativeEvent.button===2}function hC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function h0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function ZR(e,t,n=Uh){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{ZR(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function qR(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const QR=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QR(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),JR=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const tk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nk=e=>!rd(e)&&e!==tk;function Zy(){const{caseless:e}=nk(this)&&this||{},t={},n=(r,o)=>{const i=e&&ek(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=qR(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!JR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),pC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),rk=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{rk(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),p0="abcdefghijklmnopqrstuvwxyz",mC="0123456789",ok={DIGIT:mC,ALPHA:p0,ALPHA_DIGIT:p0+p0.toUpperCase()+mC},qF=(e=16,t=ok.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:QR,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:JR,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:pC,hasOwnProp:pC,reduceDescriptors:rk,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:ek,global:tk,isContextDefined:nk,ALPHABET:ok,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ik=ut.prototype,sk={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sk[e]={value:e}});Object.defineProperties(ut,sk);Object.defineProperty(ik,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(ik);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function ak(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function gC(e,t,n){return e?e.concat(t).map(function(o,i){return o=ak(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||p,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function p(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=ak(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?gC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(gC(E,S,i),f(x)),!1)}const m=[],g=Object.assign(oj,{defaultVisitor:p,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));m.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),m.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function vC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const lk=rx.prototype;lk.append=function(t,n){this._pairs.push([t,n])};lk.toString=function(t){const n=t?function(r){return t.call(this,r,vC)}:vC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ck(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const yC=sj,uk={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},dk=typeof window<"u"&&typeof document<"u",dj=(e=>dk&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:dk,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:uk,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(fk(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},wC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function m0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const p=uu(u);if(!p)throw new Error("header name must be a non-empty string");const m=ie.findKey(o,p);(!m||o[m]===void 0||f===!0||f===void 0&&o[m]!==!1)&&(o[m||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,p)=>i(f,p,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||m0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||m0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||m0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[wC]=this[wC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function g0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function hk(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function pk(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),p=r[i];s||(s=f),n[o]=u,r[o]=f;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const p={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};p[t?"download":"upload"]=!0,e(p)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let p;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((p=i.getContentType())!==!1){const[S,...E]=p?p.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=pk(e.baseURL,e.url);m.open(e.method.toUpperCase(),ck(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const S=xi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:S,config:e,request:m};Ej(function(C){n(C),f()},function(C){r(C),f()},_),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||uk;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&ie.forEach(i.toJSON(),function(E,_){m.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",xC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",xC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{m&&(r(!S||S.type?new Dd(null,e,m):S),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const bC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,mk={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(bC).join(` +`):" "+bC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function v0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function SC(e){return v0(e),e.headers=xi.from(e.headers),e.data=g0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),mk.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return v0(e),r.data=g0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return hk(r)||(v0(e),r&&r.response&&(r.response.data=g0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const _C=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,p,m){return ie.isPlainObject(f)&&ie.isPlainObject(p)?ie.merge.call({caseless:m},f,p):ie.isPlainObject(p)?ie.merge({},p):ie.isArray(p)?p.slice():p}function o(f,p,m){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f,m)}else return r(f,p,m)}function i(f,p){if(!ie.isUndefined(p))return r(void 0,p)}function s(f,p){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,p)}function l(f,p,m){if(m in t)return r(f,p);if(m in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,p)=>o(_C(f),_C(p),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(p){const m=u[p]||o,g=m(e[p],t[p],p);ie.isUndefined(g)&&m!==l||(n[p]=g)}),n}const gk="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const EC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+gk+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!EC[s]&&(EC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new yC,response:new yC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let p,m=0,g;if(!u){const x=[SC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,p=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function vk(e){const t=new Gh(e),n=qR(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return vk(ic(e,o))},n}const Qt=vk(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=hk;Qt.VERSION=gk;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>fk(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=mk.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const m=await f.blob();return{blob:URL.createObjectURL(m),seed:f.headers.get("X-Seed")}}const p=await f.json();throw new Error(`Something went wrong: ${p.errors}`)}async function yk(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function y0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function wk(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],xk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],bk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const CC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,$C=VR,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const p=n==null?void 0:n[f],m=i==null?void 0:i[f];if(p===null)return null;const g=CC(p)||CC(m);return o[f][g]}),l=n&&Object.entries(n).reduce((f,p)=>{let[m,g]=p;return g===void 0||(f[m]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,p)=>{let{class:m,className:g,...y}=p;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,m,g]:f},[]);return $C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const p=od(i.serialize),m=()=>{const E=i.partialize({...r()});let _;const b=p({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),m()};const y=e((...E)=>{n(...E),m()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),m()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const p=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},m=o.setState;o.setState=(S,E)=>{m(S,E),p()};const g=e((...S)=>{n(...S),p()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),p()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ek(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&_k(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function Ck(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kC(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function TC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function PC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Sk?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>AC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>AC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function AC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(Ek(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ck(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===w0(e.base_,t)?(x0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=$k(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=w0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;x0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return w0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,x0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function w0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=$k(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function $k(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function x0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,p=>n.call(this,p,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=TC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return kC(i,r),PC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Sk&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=TC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return kC(r,t),PC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:Ck()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),Rk(e)}function Rk(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{Ek(n,r,Rk(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var kk={exports:{}},Tk={},Pk={exports:{}},Ak={};/** + * @license React + * use-sync-external-store-shim.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. + */var lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,b0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return b0(o)&&i({inst:o}),e(function(){b0(o)&&i({inst:o})})},[e]),Vz(n),n}function b0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;Ak.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;Pk.exports=Ak;var Gz=Pk.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;Tk.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,p=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Zz(p,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(p=y,m=S)}var f=!1,p,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};kk.exports=Tk;var nB=kk.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const MC=e=>{let t;const n=new Set,r=(u,f)=>{const p=typeof u=="function"?u(t):u;if(!Object.is(p,t)){const m=t;t=f??typeof p!="object"?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?MC(e):MC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const OC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?OC(e,t):OC,uB=1,dB=1e6;let S0=0;function fB(){return S0=(S0+1)%Number.MAX_VALUE,S0.toString()}const _0=new Map,NC=e=>{if(_0.has(e))return;const t=setTimeout(()=>{_0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);_0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?NC(n):e.toasts.forEach(r=>{NC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M SDE Karras"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},xt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Uh);try{const f=await dC(u);e(p=>{p.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:p,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=m.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=p,_=x):(b=m,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_,Uh);if(E){const O=await dC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,uC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await wk(n,r,u,o.upscale),{blob:p}=f;if(n){const y=new Image;await Vh(y,p),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,p),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==XR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:p}=t();switch(l=f,u=p,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(p*(r-1)/2),u=Math.ceil(p*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(p*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(p*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Uh),f=uC(u.toDataURL()),p=await Gj(f,n,l),m=await mF(p);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Bm=d.forwardRef(({className:e,type:t,...n},r)=>{const o=xt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:_e("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Bm.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let p=u.target.value;if(t){if(p=p.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),p.length===0){n(0);return}n(parseFloat(p))}else{if(p=p.replace(/\D/g,""),p.length===0){n(0);return}n(parseInt(p,10))}s(p)};return v.jsx(Bm,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(m){const{scope:g,children:y,...x}=m,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function p(m,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,p]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(i)[`__scope${f}`];return{...l,...m}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let DC;const Mk=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,p=d.useContext(Mk),[m,g]=d.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=m?E.indexOf(m):-1,R=p.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...p.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...p.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===p.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(m)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(DC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(m)),p.layers.add(m),IC(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=DC)}},[m,y,r,p]),d.useEffect(()=>()=>{m&&(p.layers.delete(m),p.layersWithOutsidePointerEventsDisabled.delete(m),IC())},[m,p]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(Mk),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let p=function(){Ok(yB,n,f,{discrete:!0})};var u=p;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=p,t.addEventListener("click",o.current,{once:!0})):p()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ok(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function IC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function Ok(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=U9.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,dh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nk(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function LC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",p=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:p,y:r.y-o.height};break;case"bottom":y={x:p,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:p,y:m}=LC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:p=0}=Ci(e,t)||{};if(f==null)return{};const m=Nk(p),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(m[_],B),J=Ts(m[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function jC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function zC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=jC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:zC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=jC(i,n.floating);return{data:{escapedOffsets:s,escaped:zC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,p=i&&u?-1:1,m=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*p,y:g*f}:{x:g*f,y:y*p}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},p=await ld(t,u),m=$c($i(o)),g=fx(m);let y=f[g],x=f[m];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+p[E],C=y-p[_];y=c1(b,y,C)}if(s){const E=m==="y"?"top":"left",_=m==="y"?"bottom":"right",b=x+p[E],C=x-p[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[m]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),p={x:n,y:r},m=$c(o),g=fx(m);let y=p[g],x=p[m];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[m]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[m])||0)+(R?0:E.crossAxis),O=i.reference[m]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[m])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[m]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),p=Cc(n),m=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=p===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=p==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(m){const O=g-u.left-u.right;R=p||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=p||b?Ts(E,O):O}if(b&&!p){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);m?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return Dk(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(Dk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dk(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function BC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ld(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Um(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Um(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Vm(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||BC(e)&&e.host||Mi(e);return BC(t)?t.host:t}function Ik(e){const t=cc(e);return Um(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Ld(t)?t:Ik(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ik(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ld(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function Lk(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Lk(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function Fk(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?Fk(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,p=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,p*=S.x,m*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:p,height:m,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Ld(i))&&(s=Vm(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function jk(e){return Na(Mi(e)).left+Vm(e).scrollLeft}function XB(e){const t=Mi(e),n=Vm(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+jk(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function UC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=Fk(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function zk(e,t){const n=cc(e);return n===t||!Ri(n)||Um(n)?!1:Xr(n).position==="fixed"||zk(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Um(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ld(s)&&!u&&zk(e,s))?r=r.filter(p=>p!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,p)=>{const m=UC(t,p,o);return f.top=hr(m.top,f.top),f.right=Ts(m.right,f.right),f.bottom=Ts(m.bottom,f.bottom),f.left=hr(m.left,f.left),f},UC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return Lk(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Ld(o))&&(l=Vm(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=jk(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function VC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function Bk(e,t){const n=vr(e);if(!qo(e))return n;let r=VC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=VC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||Bk,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:Bk,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:p,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=dh(p),x=dh(o.clientWidth-(f+m)),S=dh(o.clientHeight-(p+g)),E=dh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),p=o||i?[...f?cd(f):[],...cd(t)]:[];p.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const m=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{p.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?FC({element:r.current,padding:o}).fn(n):{}:r?FC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!jp(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Uk(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function WC(e,t){const n=Uk(e);return Math.round(t*n)/n}function HC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[p,m]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(p),B=HC(u),V=HC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{m(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=WC(U.floating,p.x),H=WC(U.floating,p.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...Uk(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,p.x,p.y]);return d.useMemo(()=>({...p,update:J,refs:se,elements:U,floatingStyles:ne}),[p,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Vk="Popper",[Wk,Fs]=Mn(Vk),[uU,Hk]=Wk(Vk),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Hk(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),Kk="PopperContent",[pU,pte]=Wk(Kk),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:p,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=Hk(Kk,p),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=m+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=Gk(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:p,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,m=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,S]=Gk(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=m?E:`${_}px`,R=`${-y}px`):x==="top"?(C=m?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=m?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=m?E:`${b}px`),{data:{x:C,y:R}}}});function Gk(e){const[t,n="center"]=e.split("-");return[t,n]}const Fd=dU,Wm=hU,Hm=mU,jd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=fh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,p=o.current;if(p!==e){const g=i.current,y=fh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(p&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=m=>{const y=fh(r.current).includes(m.animationName);m.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},p=m=>{m.target===t&&(i.current=fh(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function fh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Km=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Km,[Gm,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Gm(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(p=>{u.current=p},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Ym]=Gm(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[p,m]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(Fd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:p,onTriggerChange:m,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},KC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ym(KC,n),i=xx(KC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),p=d.useRef(!1),m=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),d.createElement(Wm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!p.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Gm(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Ym(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(Yk,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Ym(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,p=o.current,{onPointerInTransitChange:m}=r,g=d.useCallback(()=>{l(null),m(!1)},[m]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),m(!0)},[m]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&p){const x=E=>y(E,p),S=E=>y(E,u);return u.addEventListener("pointerleave",x),p.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),p.removeEventListener("pointerleave",S)}}},[u,p,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(p==null?void 0:p.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,p,s,f,g]),d.createElement(Yk,Y({},e,{ref:i}))}),[OU,vte]=Gm(bx,{isInside:!1}),Yk=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Ym(ud,n),f=wx(n),{onClose:p}=u;return d.useEffect(()=>(document.addEventListener(d1,p),()=>document.removeEventListener(d1,p)),[p]),d.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&p()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,p]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:p},d.createElement(Hm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.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)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,Xk=AU,VU=zU,Zk=BU,qk=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(Xk,{ref:r,sideOffset:t,className:_e("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=Xk.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:_e(_x({variant:t,size:n,className:e}),"outline-none cursor-default select-none"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Bm,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={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"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([p,m])=>d.createElement(p,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("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"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),Qk=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("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"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("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"}]]),sV=Jt("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"}]]),GC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),YC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),Jk=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function eT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const E0="focusScope.autoFocusOnMount",C0="focusScope.autoFocusOnUnmount",XC={bubbles:!1,cancelable:!0},Xm=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),p=Ft(i),m=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?m.current=A:Qi(m.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(m.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){qC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(E0,XC);l.addEventListener(E0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(tT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(E0,f),setTimeout(()=>{const _=new CustomEvent(C0,XC);l.addEventListener(C0,p),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(C0,p),qC.remove(y)},0)}}},[l,f,p,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=tT(e),n=ZC(t,e),r=ZC(t.reverse(),e);return[n,r]}function tT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function ZC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const qC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=QC(e,t),e.unshift(t)},remove(t){var n;e=QC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function QC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let $0=0;function Zm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:JC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:JC()),$0++,()=>{$0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),$0--}},[])}function JC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=iT(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var hh=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",hh,hh),window.removeEventListener("test",hh,hh)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},sT=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return sT(e,"overflowY")},jV=function(e){return sT(e,"overflowX")},t2=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=aT(e,n);if(r){var o=lT(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},aT=function(e,t){return e==="v"?FV(t):jV(t)},lT=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,p=s>0,m=0,g=0;do{var y=lT(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&aT(e,l)&&(m+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(p&&(o&&m===0||!o&&s>m)||!p&&(o&&g===0||!o&&-s>g))&&(f=!0),f},ph=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},n2=function(e){return[e.deltaX,e.deltaY]},r2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return iT()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(r2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=ph(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=t2(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=t2(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?n2(E):ph(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(r2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),p=d.useCallback(function(S){n.current=ph(S),r.current=void 0},[]),m=d.useCallback(function(S){f(S.type,n2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,ph(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",p,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",p,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(oT,GV);var cT=d.forwardRef(function(e,t){return d.createElement(qm,Lo({},e,{ref:t,sideCar:YV}))});cT.classNames=qm.classNames;const Qm=cT;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,mh=new WeakMap,gh={},T0=0,uT=function(e){return e&&(e.host||uT(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=uT(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);gh[n]||(gh[n]=new WeakMap);var i=gh[n],s=[],l=new Set,u=new Set(o),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};o.forEach(f);var p=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))p(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&mh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return p(t),l.clear(),T0++,function(){s.forEach(function(m){var g=il.get(m)-1,y=i.get(m)-1;il.set(m,g),i.set(m,y),g||(mh.has(m)||m.removeAttribute(r),mh.delete(m)),y||m.removeAttribute(n)}),T0--,T0||(il=new WeakMap,il=new WeakMap,mh=new WeakMap,gh={})}},Jm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const dT="Dialog",[fT,hT]=Mn(dT),[QV,Eo]=fT(dT),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,p]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(m=>!m),[p]),modal:s},n)},eW="DialogTrigger",pT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),mT="DialogPortal",[tW,gT]=fT(mT,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(mT,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=gT(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(Qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=gT(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(vT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(vT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),vT=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Zm(),d.createElement(d.Fragment,null,d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),yT="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(yT,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",wT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:yT,docsSlug:"dialog"}),Cx=JV,xT=pT,$x=nW,zd=rW,Bd=iW,Ud=lW,Vd=wT,Rx=dW,eg=Cx,kx=xT,pW=$x,bT=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{ref:n,className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bT.displayName=zd.displayName;const Wd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(bT,{}),v.jsxs(Bd,{ref:r,className:_e("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(bk,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Wd.displayName=Bd.displayName;const ST=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});ST.displayName="DialogHeader";const Hd=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-2xl font-semibold leading-none tracking-tight",e),...t}));Hd.displayName=Ud.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));mW.displayName=Vd.displayName;function m1(){return m1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,p=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(m),_=p.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function RT(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&RT(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return RT(t.current,e)||(t.current=e),t.current}var o2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),p=d.useRef(f);u?p.current=f:p.current=t;var m=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!$T(R,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){o2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||P0(l,m==null?void 0:m.splitKey).forEach(function(A){var D,B=A0(A,m==null?void 0:m.combinationKey);if(_W(R,B,m==null?void 0:m.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,m==null?void 0:m.preventDefault),!xW(R,B,m==null?void 0:m.enabled)){o2(R);return}p.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(ET(hs(R.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&S(R))},_=function(R){R.key!==void 0&&(CT(hs(R.code)),i.current=!1,m!=null&&m.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.addHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.removeHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=xt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},vh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=eT(!1);return Zn("h",()=>{t()}),v.jsxs(eg,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Wd,{children:v.jsxs(ST,{children:[v.jsx(Hd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[vh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[vh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[vh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[vh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const kT="Popover",[TT,wte]=Mn(kT,[Fs]),Ax=Fs(),[OW,Rc]=TT(kT),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,p]=d.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Fd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>p(!0),[]),onCustomAnchorRemove:d.useCallback(()=>p(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":MT(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Wm,Y({asChild:!0},i),l)}),PT="PopoverPortal",[LW,FW]=TT(PT,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(PT,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Jm(s)},[]),d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(AT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(AT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),AT=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:p,...m}=e,g=Rc(dd,n),y=Ax(n);return Zm(),d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Hm,Y({"data-state":MT(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function MT(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,OT=zW,KW=VW,GW=WW,NT=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(OT,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:_e("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));NT.displayName=OT.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const r=xt(s=>s.updateAppState),o=()=>{r({disableShortCuts:!0})},i=()=>{r({disableShortCuts:!1})};return v.jsx("textarea",{className:_e("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50","overflow-auto",e),tabIndex:-1,ref:n,onFocus:o,onBlur:i,...t})});Dx.displayName="Textarea";const yH=()=>{const[e,t,n,r,o,i]=xt(x=>[x.getIsProcessing(),x.settings.prompt,x.updateSettings,x.runInpainting,x.showPrevMask,x.hidePrevMask]),[s,l]=Nx(!1),u=d.useRef(null);DT(u,()=>{u!=null&&u.current&&u.current.blur()});const f=x=>{x.preventDefault(),x.stopPropagation();const S=x.target;n({prompt:S.value})},p=()=>{e||r()},m=x=>{x.key==="Enter"&&x.ctrlKey&&t.length!==0&&p()},g=()=>{o()},y=()=>{i()};return v.jsx("div",{className:"flex gap-4 relative w-full justify-center h-full",children:v.jsxs("div",{className:"absolute flex gap-4",children:[v.jsx(Dx,{ref:u,placeholder:"I want to repaint of...",className:_e(s?"focus:overflow-y-auto":"overflow-y-hidden","min-h-[32px] h-[32px] overflow-x-hidden focus:h-[120px] overflow-y-hidden transition-[height] w-[500px] py-1 px-3 bg-background resize-none"),style:{scrollbarGutter:"stable"},value:t,onInput:f,onKeyUp:m,onTransitionEnd:l}),v.jsx(wn,{size:"sm",onClick:p,disabled:e,onMouseEnter:g,onMouseLeave:y,children:"Paint"})]})})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,p="__lodash_placeholder__",m=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",Sg=/\b__p \+= '';/g,_g=/\b(__p \+=) '' \+/g,Qd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),Eg=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,Jd=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Cg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$g=/^\w*$/,Rg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ef=/\{\n\/\* \[wrapped with (.+)\] \*/,a6=/,? & /,l6=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,c6=/[()=,{}\[\]\/\s]/,u6=/\\(\\)?/g,d6=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,mb=/\w*$/,f6=/^[-+]0x[0-9a-f]+$/i,h6=/^0b[01]+$/i,p6=/^\[object .+?Constructor\]$/,m6=/^0o[0-7]+$/i,g6=/^(?:0|[1-9]\d*)$/,v6=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,tf=/($^)/,y6=/['\n\r\u2028\u2029\\]/g,nf="\\ud800-\\udfff",w6="\\u0300-\\u036f",x6="\\ufe20-\\ufe2f",b6="\\u20d0-\\u20ff",gb=w6+x6+b6,vb="\\u2700-\\u27bf",yb="a-z\\xdf-\\xf6\\xf8-\\xff",S6="\\xac\\xb1\\xd7\\xf7",_6="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",E6="\\u2000-\\u206f",C6=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",wb="A-Z\\xc0-\\xd6\\xd8-\\xde",xb="\\ufe0e\\ufe0f",bb=S6+_6+E6+C6,kg="['’]",$6="["+nf+"]",Sb="["+bb+"]",rf="["+gb+"]",_b="\\d+",R6="["+vb+"]",Eb="["+yb+"]",Cb="[^"+nf+bb+_b+vb+yb+wb+"]",Tg="\\ud83c[\\udffb-\\udfff]",k6="(?:"+rf+"|"+Tg+")",$b="[^"+nf+"]",Pg="(?:\\ud83c[\\udde6-\\uddff]){2}",Ag="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+wb+"]",Rb="\\u200d",kb="(?:"+Eb+"|"+Cb+")",T6="(?:"+Ua+"|"+Cb+")",Tb="(?:"+kg+"(?:d|ll|m|re|s|t|ve))?",Pb="(?:"+kg+"(?:D|LL|M|RE|S|T|VE))?",Ab=k6+"?",Mb="["+xb+"]?",P6="(?:"+Rb+"(?:"+[$b,Pg,Ag].join("|")+")"+Mb+Ab+")*",A6="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",M6="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ob=Mb+Ab+P6,O6="(?:"+[R6,Pg,Ag].join("|")+")"+Ob,N6="(?:"+[$b+rf+"?",rf,Pg,Ag,$6].join("|")+")",D6=RegExp(kg,"g"),I6=RegExp(rf,"g"),Mg=RegExp(Tg+"(?="+Tg+")|"+N6+Ob,"g"),L6=RegExp([Ua+"?"+Eb+"+"+Tb+"(?="+[Sb,Ua,"$"].join("|")+")",T6+"+"+Pb+"(?="+[Sb,Ua+kb,"$"].join("|")+")",Ua+"?"+kb+"+"+Tb,Ua+"+"+Pb,M6,A6,_b,O6].join("|"),"g"),F6=RegExp("["+Rb+nf+gb+xb+"]"),j6=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,z6=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],B6=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var U6={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},V6={"&":"&","<":"<",">":">",'"':""","'":"'"},W6={"&":"&","<":"<",">":">",""":'"',"'":"'"},H6={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},K6=parseFloat,G6=parseInt,Nb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,Y6=typeof self=="object"&&self&&self.Object===Object&&self,fn=Nb||Y6||Function("return this")(),Og=t&&!t.nodeType&&t,Hs=Og&&!0&&e&&!e.nodeType&&e,Db=Hs&&Hs.exports===Og,Ng=Db&&Nb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Ng&&Ng.binding&&Ng.binding("util")}catch{}}(),Ib=$r&&$r.isArrayBuffer,Lb=$r&&$r.isDate,Fb=$r&&$r.isMap,jb=$r&&$r.isRegExp,zb=$r&&$r.isSet,Bb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function X6(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Dg(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Xb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oM(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iM=jg(U6),sM=jg(V6);function aM(F){return"\\"+H6[F]}function lM(F,te){return F==null?n:F[te]}function Wa(F){return F6.test(F)}function cM(F){return j6.test(F)}function uM(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Vg(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Zb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qM(a,c){var h=this.__data__,w=Sf(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GM,ti.prototype.delete=YM,ti.prototype.get=XM,ti.prototype.has=ZM,ti.prototype.set=qM;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&m,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tO(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return MS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:qS(a),!I)return z?W7(a,h7(N,a)):V7(a,lS(N,a))}else{if(!Et[ae])return $?a:{};N=nO(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),$_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):E_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?mv:pv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p7(a){var c=ln(a);return function(h){return cS(h,a,c)}}function cS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function uS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=of,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Dg,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:k_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Zg=FS(),hS=FS(!0);function $o(a,c){return a&&Zg(a,c,ln)}function qg(a,c){return a&&hS(a,c,ln)}function Ef(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v7(a,c){return a!=null&&yt.call(a,c)}function y7(a,c){return a!=null&&c in St(a)}function w7(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&mf.call(I,z,1),mf.call(a,z,1);return a}function ES(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?mf.call(a,$,1):av(a,$)}}return a}function ov(a,c){return a+yf(oS()*(c-a+1))}function M7(a,c,h,w){for(var $=-1,T=tn(vf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function iv(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=yf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return Sv(e_(a,c,Gn),a+"")}function O7(a){return aS(tl(a))}function N7(a,c){var h=tl(a);return Df(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L7(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function $f(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y7(a);if(re)return af(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var AS=CM||function(a){return fn.clearTimeout(a)};function MS(a,c){if(c)return a.slice();var h=a.length,w=Jb?Jb(h):new a.constructor(h);return a.copy(w),w}function dv(a){var c=new a.constructor(a.byteLength);return new hf(c).set(new hf(a)),c}function j7(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z7(a){var c=new a.constructor(a.source,mb.exec(a));return c.lastIndex=a.lastIndex,c}function B7(a){return Vc?St(Vc.call(a)):{}}function OS(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function NS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function DS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function LS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function FS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H7(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function jS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Ig(L_(I_(c).replace(D6,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K7(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function BS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Of(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oO(a){return Ge(a)||Js(a)||!!(nS&&a&&a[nS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&g6.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Df(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,f_(a,h)});function h_(a){var c=k(a);return c.__chain__=!0,c}function m4(a,c){return c(a),a}function If(a,c){return c(a)}var g4=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Xg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:If,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v4(){return h_(this)}function y4(){return new Tr(this.value(),this.__chain__)}function w4(){this.__values__===n&&(this.__values__=R_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x4(){return this}function b4(a){for(var c,h=this;h instanceof bf;){var w=s_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S4(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:If,args:[_v],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(_v)}function _4(){return TS(this.__wrapped__,this.__actions__)}var E4=kf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C4(a,c,h){var w=Ge(a)?Ub:m7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $4(a,c){var h=Ge(a)?Li:fS;return h(a,Ie(c,3))}var R4=zS(a_),k4=zS(l_);function T4(a,c){return hn(Lf(a,c),1)}function P4(a,c){return hn(Lf(a,c),ee)}function A4(a,c,h){return h=h===n?1:qe(h),hn(Lf(a,c),h)}function p_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function m_(a,c){var h=Ge(a)?Z6:dS;return h(a,Ie(c,3))}var M4=kf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O4(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Uf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N4=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D4=kf(function(a,c,h){ri(a,h,c)});function Lf(a,c){var h=Ge(a)?Ot:yS;return h(a,Ie(c,3))}function I4(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),SS(a,c,h))}var L4=kf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F4(a,c,h){var w=Ge(a)?Ig:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j4(a,c,h){var w=Ge(a)?q6:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,dS)}function z4(a,c){var h=Ge(a)?Li:fS;return h(a,zf(Ie(c,3)))}function B4(a){var c=Ge(a)?aS:O7;return c(a)}function U4(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u7:N7;return w(a,c)}function V4(a){var c=Ge(a)?d7:I7;return c(a)}function W4(a){if(a==null)return 0;if(Hn(a))return Uf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:tv(a).length}function H4(a,c,h){var w=Ge(a)?Lg:L7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K4=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),SS(a,hn(c,1),[])}),Ff=$M||function(){return fn.Date.now()};function G4(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function g_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function v_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Cv=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Cv));w|=P}return oi(a,w,c,h,$)}),y_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(y_));w|=P}return oi(c,w,a,h,$)});function w_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=w_.placeholder,w}function x_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=x_.placeholder,w}function b_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,z_=c-no;return ae?En(z_,T-ci):z_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=Ff();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&AS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(Ff())}function cr(){var Yt=Ff(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return AS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y4=et(function(a,c){return uS(a,1,c)}),X4=et(function(a,c,h){return uS(a,Or(c)||0,h)});function Z4(a){return oi(a,B)}function jf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(jf.Cache||ni),h}jf.Cache=ni;function zf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q4(a){return v_(2,a)}var Q4=F7(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=mS(function(){return arguments}())?mS:function(a){return Bt(a)&&yt.call(a,"callee")&&!tS.call(a,"callee")},Ge=Q.isArray,hN=Ib?ir(Ib):b7;function Hn(a){return a!=null&&Bf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function pN(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kM||Lv,mN=Lb?ir(Lb):S7;function gN(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function vN(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!tv(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function yN(a,c){return Gc(a,c)}function wN(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function Rv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function xN(a){return typeof a=="number"&&rS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function __(a){return typeof a=="number"&&a==qe(a)}function Bf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var E_=Fb?ir(Fb):E7;function bN(a,c){return a===c||ev(a,c,vv(c))}function SN(a,c,h){return h=typeof h=="function"?h:n,ev(a,c,vv(c),h)}function _N(a){return C_(a)&&a!=+a}function EN(a){if(aO(a))throw new Ke(i);return gS(a)}function CN(a){return a===null}function $N(a){return a==null}function C_(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=pf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&uf.call(h)==SM}var kv=jb?ir(jb):C7;function RN(a){return __(a)&&a>=-H&&a<=H}var $_=zb?ir(zb):$7;function Uf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=Bb?ir(Bb):R7;function kN(a){return a===n}function TN(a){return Bt(a)&&Cn(a)==ke}function PN(a){return Bt(a)&&On(a)==ft}var AN=Mf(nv),MN=Mf(function(a,c){return a<=c});function R_(a){if(!a)return[];if(Hn(a))return Uf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uM(a[jc]());var c=Cn(a),h=c==ct?Vg:c==q?af:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function k_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Gb(a);var h=h6.test(a);return h||m6.test(a)?G6(a.slice(2),h?2:8):f6.test(a)?W:+a}function T_(a){return Ro(a,Kn(a))}function ON(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var NN=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),P_=qa(function(a,c){Ro(c,Kn(c),a)}),Vf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),DN=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),IN=ii(Xg);function LN(a,c){var h=Za(a);return c==null?h:lS(h,c)}var FN=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,mv(a),h),w&&(h=Pr(h,m|g|y,X7));for(var $=c.length;$--;)av(h,c[$]);return h});function n8(a,c){return M_(a,zf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P7(a,c)});function M_(a,c){if(a==null)return{};var h=Ot(mv(a),function(w){return[w]});return c=Ie(c),_S(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var O_=HS(ln),N_=HS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(pf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:av(a,c)}function c8(a,c,h){return a==null?a:kS(a,c,uv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:kS(a,c,uv(h),w)}function tl(a){return a==null?[]:Ug(a,ln(a))}function d8(a){return a==null?[]:Ug(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w7(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=oS();return En(a+$*(c-a+K6("1e-"+(($+"").length-1))),c)}return ov(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?D_(c):c)});function D_(a){return Av(vt(a).toLowerCase())}function I_(a){return a=vt(a),a&&a.replace(v6,iM).replace(I6,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&Eg.test(a)?a.replace(Nc,sM):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=jS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Af(yf($),h)+a+Af(vf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!kv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Av(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Vf({},c,w,KS);var $=Vf({},c.imports,w.imports,KS),T=ln($),N=Ug($,T),I,z,re=0,oe=c.interpolate||tf,ae="__p += '",ge=Wg((c.escape||tf).source+"|"+oe.source+"|"+(oe===Lc?d6:tf).source+"|"+(c.evaluate||tf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++B6+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(y6,aM),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(c6.test(Le))throw new Ke(l);ae=(z?ae.replace(Sg,""):ae).replace(_g,"$1").replace(Qd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=F_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,Rv(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Gb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Yb(w,$),N=Xb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,qb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Xb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Yb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),kv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Wg($.source,vt(mb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pM):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Av=jS("toUpperCase");function L_(a,c,h){return a=vt(a),c=h?n:c,c===n?cM(a)?vM(a):eM(a):a.match(c)||[]}var F_=et(function(a,c){try{return or(a,n,c)}catch(h){return Rv(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Cv(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=Bg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:If,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=lf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Tf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jM,ot.prototype.reverse=zM,ot.prototype.value=BM,k.prototype.at=g4,k.prototype.chain=v4,k.prototype.commit=y4,k.prototype.next=w4,k.prototype.plant=b4,k.prototype.reverse=S4,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_4,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x4),k},Ka=yM();Hs?((Hs.exports=Ka)._=Ka,Og._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((p,m)=>{const g=u+p,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function IT(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=IT(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:p}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,p);if(S===void 0)break;m.set(x,S)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const p=[];for(let m=1;m({photo:x,index:S})).slice(f[m-1],f[m]),y=IT(g.map(({photo:x})=>x),o,n,r);p.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return p}function tg(...e){return[...e].filter(t=>!!t).join(" ")}function LT(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:LT("100%",e,t)}function c2(e,t,n){var r,o;return LT((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${c2(l,t,n)}`).concat(c2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ix(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:p}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{p({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:tg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(m);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:tg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:p,weight:m})=>{let g=o.get(p);g||(g=[],o.set(p,g));const y=f+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function u2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,p)=>f+p,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),m=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[f]/u;l.push(p.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:p.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,p=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),m=LH(p,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=u2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function FT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:p}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return p.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?FT({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:p,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return FT({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((m,g)=>m+g,0),p=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+p,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function jT(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:tg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:p}=l;return d.createElement(d.Fragment,null,u.map((m,g)=>d.createElement(jT,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:p,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>d.createElement(Ix,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function zT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?zT({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let p=0;p{const y=u.reduce((x,S,E)=>S[])).map(p=>p.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:p.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zT({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(jT,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:tg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Lx(e,t){return typeof e=="function"?e(t):e}function BT(e,t){return typeof e<"u"?Lx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Lx(e[n>=0?n:0],t)}function yh(e,t,n,r=0){const o=BT(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:yh(i,n,[5,4,3,2],1),spacing:yh(s,n,[20,15,10,5]),padding:yh(l,n,[0,0,0,0,0]),targetRowHeight:yh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:BT(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Lx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:p}=f||{};if(p){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*p-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):WT(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function UT(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&WT(e)=="[object Boolean]"}function VT(e){return typeof e=="object"}function gK(e){return VT(e)&&e!==null}function pr(e){return e!=null}function M0(e){return!e.trim().length}function WT(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,d2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=HT(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function HT(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=f2(e),n=g1(e);else{if(!d2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,d2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=f2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function f2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||UT(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let p=0,m=f.length;pe.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:p}=u.pop();if(pr(p))if(Bo(p)&&!M0(p)){let m={v:p,i:f,n:this.norm.get(p)};l.push(m)}else ki(p)&&p.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Bo(s)&&!M0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function KT(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Fx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(HT)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Fx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function wh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const p=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const S=l>1||u,E=S?Array(m):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=wh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+p,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=wh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(wh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>la){let g=0;const y=m%la,x=m-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),m+=b,_&&C&&(p=[...p,...C])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=p),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return h2(t,this.multiRegex)}static isSingleMatch(t){return h2(t,this.singleRegex)}search(){}}function h2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class YT extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new GT(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class XT extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,XT,IK,LK,jK,FK,DK,YT],p2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&VT(e)&&!b1(e),m2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function ZT(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(m2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const p={keyId:g1(u),pattern:f};return n&&(p.searcher=w1(f,t)),p}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(p=>{l.children.push(r(p))})}),l};return b1(e)||(e=m2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Fx))throw new Error(vK);this._myIndex=n||KT(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:p}]})}),o}_searchLogical(t){const n=ZT(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const p=[];for(let m=0,g=l.children.length;m{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:p})=>{i[u].matches.push(...p)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,p)=>{u.push(...this._findMatches({key:f,value:s[p],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:p})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=KT;kc.parseIndex=PK;kc.config=He;kc.parseQuery=ZT;HK(WK);function Kd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",p="data-radix-collection-item",m=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[p]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${p}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const O0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},jx="RovingFocusGroup",[S1,qT,eG]=Kd(jx),[tG,ng]=Mn(jx,[eG]),[nG,rG]=tG(jx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...p}=e,m=d.useRef(null),g=Ue(t,m),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=qT(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(O0,b),()=>A.removeEventListener(O0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},p,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(O0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);QT(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),p=f.currentTabStopId===u,m=qT(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:p?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=m().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>QT(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function QT(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const JT=oG,e3=aG,t3="Tabs",[fG,xte]=Mn(t3,[ng]),n3=ng(),[hG,zx]=fG(t3),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,p=Tc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:p,activationMode:u},d.createElement(Ae.div,Y({dir:p,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=zx(mG,n),s=n3(n);return d.createElement(JT,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=zx(vG,n),l=n3(n),u=r3(s.baseId,r),f=o3(s.baseId,r),p=r===s.value;return d.createElement(e3,Y({asChild:!0},l,{focusable:!o,active:p}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":p,"aria-controls":f,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!p&&!o&&m&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=zx(wG,n),u=r3(l.baseId,r),f=o3(l.baseId,r),p=r===l.value,m=d.useRef(p);return d.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||p},({present:g})=>d.createElement(Ae.div,Y({"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function r3(e,t){return`${e}-trigger-${t}`}function o3(e,t){return`${e}-content-${t}`}const bG=pG,i3=gG,s3=yG,a3=xG,l3=bG,Bx=d.forwardRef(({className:e,...t},n)=>v.jsx(i3,{ref:n,className:_e("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Bx.displayName=i3.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(s3,{ref:n,className:_e("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=s3.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(a3,{ref:n,className:_e("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=a3.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function Ux(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],rg="Select",[og,ig,EG]=Kd(rg),[Pc,bte]=Mn(rg,[EG,Fs]),Vx=Fs(),[CG,Fa]=Pc(rg),[$G,RG]=Pc(rg),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:p,autoComplete:m,disabled:g,required:y}=e,x=Vx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(Fd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(og.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(h3,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:p,autoComplete:m,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Vx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=ig(n),[p,m,g]=p3(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=m3(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Wm,Y({asChild:!0},i),d.createElement(Ae.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":f3(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=p.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,p=i!==void 0,m=Ue(t,u.onValueNodeChange);return An(()=>{f(p)},[f,p]),d.createElement(Ae.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),f3(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(jd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(c3,{scope:e.__scopeSelect},d.createElement(og.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[c3,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=ig(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Jm(C)},[C]),Zm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=p3(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=m3(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?g2:LG,Ne=We===g2?{side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(c3,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(Xm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ue(t,A=>p(A)),g=ig(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),g2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Vx(n);return d.createElement(Hm,Y({},s,i,{ref:t,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)"}}))}),[FG,Wx]=Pc(dc,{}),v2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(v2,n),i=Wx(v2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(og.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&p){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(x,S);if(E0?C:0,p.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,u3]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[p,m]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{m(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(og.ItemSlot,{scope:n,value:r,disabled:o,textValue:p},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),xh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(xh,n),l=ja(xh,n),u=u3(xh,n),f=RG(xh,n),[p,m]=d.useState(null),g=Ue(t,_=>m(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=p==null?void 0:p.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u3(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),y2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(y2,e.__scopeSelect),r=Wx(y2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollTop>0;i(p)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),w2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(w2,e.__scopeSelect),r=Wx(w2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),d3=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=ig(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const p=l().find(m=>m.ref.current===document.activeElement);p==null||(f=p.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function f3(e){return e===""||e===void 0}const h3=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=Ux(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&p){const m=new Event("change",{bubbles:!0});p.call(l,n),l.dispatchEvent(m)}},[s,n]),d.createElement(Km,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});h3.displayName="BubbleSelect";function p3(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function m3(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,g3=PG,nY=MG,rY=OG,oY=NG,v3=DG,iY=jG,sY=VG,y3=HG,w3=GG,aY=YG,lY=ZG,x3=qG,b3=QG,S3=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g3,{ref:r,className:_e("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=g3.displayName;const _3=d.forwardRef(({className:e,...t},n)=>v.jsx(x3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));_3.displayName=x3.displayName;const E3=d.forwardRef(({className:e,...t},n)=>v.jsx(b3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));E3.displayName=b3.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(v3,{ref:o,className:_e("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(_3,{}),v.jsx(iY,{className:_e("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(E3,{})]})}));vo.displayName=v3.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:_e("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=y3.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(w3,{ref:r,className:_e("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(xk,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=w3.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(S3,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=S3.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const C3="ScrollArea",[$3,Ste]=Mn(C3),[fY,qr]=$3(C3),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,p]=d.useState(null),[m,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:p,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",R3=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(k3,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Hx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},p=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",p)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(k3,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=ag(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,p=i?"scrollLeft":"scrollTop";if(f){let m=f[p];const g=()=>{const y=f[p];m!==y&&(u("SCROLL"),s()),m=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Hx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),k3=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=ag(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=M3(l.viewport,l.content),p={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=x2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=x2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"horizontal"},o,{ref:f,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":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"vertical"},o,{ref:f,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":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,T3]=$3(Oi),P3=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:p,onResize:m,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(p),O=Ft(u),A=ag(m,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=T3(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=T3(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,m=>s.onThumbChange(m)),f=d.useRef(),p=ag(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(p(),!f.current){const y=$Y(m,l);f.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,p,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,S=m.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),A3="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(A3,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(A3,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var p;const m=((p=o.scrollbarX)===null||p===void 0?void 0:p.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),fc(o.scrollbarY,()=>{var p;const m=((p=o.scrollbarY)===null||p===void 0?void 0:p.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function M3(e,t){const n=e/t;return isNaN(n)?0:n}function sg(e){const t=M3(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=sg(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,m=r==="ltr"?[0,p]:[p*-1,0];return O3([u,f],m)(e)}function x2(e,t,n="ltr"){const r=sg(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return O3([0,s],[0,l])(f)}function O3(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function N3(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ag(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const D3=hY,RY=mY,kY=_Y,lg=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(D3,{ref:r,className:_e("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(I3,{}),v.jsx(kY,{})]}));lg.displayName=D3.displayName;const I3=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(R3,{ref:r,orientation:t,className:_e("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));I3.displayName=R3.displayName;const L3="Name",F3="Created time",j3="Modified time",b2="input",TY="output",S2={[Es.NAME]:L3,[Es.CTIME]:F3,[Es.MTIME]:j3};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=Nx(!1),[i,s]=xt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[p,m]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(b2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||m(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:p,left:0})},100)},[r,p]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(eg,{open:r,onOpenChange:o,children:[v.jsx(pT,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Wd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Hd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Bm,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(l3,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(Bx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:b2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:S2[i.sortBy],onValueChange:V=>{switch(V){case L3:s({sortBy:Es.NAME});break;case F3:s({sortBy:Es.CTIME});break;case j3:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(S2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(lg,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Gd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const z3=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&z3(e)&&!$l(e),B3=e=>sn(e)&&e.target?Gd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,U3=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Kx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Kx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Yd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Yd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},V3=je.createContext(null),cg=()=>je.useContext(V3),OY=e=>{const{children:t,...n}=e;return je.createElement(V3.Provider,{value:n},t)};var W3=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,H3=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],K3=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Gx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=cg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),p=je.useRef(o);return p.current=o,Gx({disabled:r,next:m=>u.current&&K3(p.current,m.name,i)&&H3(m,f.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),W3(s,n,f.current,!1)}var Wo=e=>typeof e=="string",G3=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=cg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Gx({disabled:i,subject:n._subjects.values,next:p=>{K3(l.current,p.name,s)&&f(so(G3(l.current,n._names,p.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Yx=e=>/^\w*$/.test(e),Y3=e=>Yd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Yx(t)?[t]:Y3(t),i=o.length,s=i-1;for(;++r{const p=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),p){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?p&&!o._state.action:p)?o.unregister(n):m(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(p=>f.current.onChange({target:{value:B3(p),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:p=>{const m=ve(o._fields,n);m&&p&&(m._f.ref={focus:()=>p.focus(),select:()=>p.select(),setCustomValidity:g=>p.setCustomValidity(g),reportValidity:()=>p.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var X3=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},_2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),E2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Yd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Xx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Kx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Zx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const C2={value:!1,isValid:!1},$2={value:!0,isValid:!0};var Z3=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?$2:{value:e[0].value,isValid:!0}:$2:C2}return C2};const R2={isValid:!1,value:null};var q3=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,R2):R2;function k2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},T2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:p,max:m,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Zx(i),A=Gd(i),D=O||A,B=(S||Xx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=X3.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!Z3(s).isValid||O&&!q3(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(p)||!Fn(m))){let G,se;const U=sl(m),ne=sl(p);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=k2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=k2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!z3(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var Q3=e=>e.type==="select-multiple",BY=e=>Zx(e)||Gd(e),D0=e=>Hp(e)&&e.isConnected,J3=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!J3(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function eP(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!J3(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:eP(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var I0=(e,t)=>eP(e,t,Yp(t)),tP=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function L0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Xx(t)?t.files:Zx(t)?q3(e.refs).value:Q3(t)?[...t.selectedOptions].map(({value:n})=>n):Gd(t)?Z3(e.refs).value:tP(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function P2(e,t,n){const r=ve(e,n);if(r||Yx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Yd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,p=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:N0(),array:N0(),state:N0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=_2(n.mode),S=_2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(p),p=setTimeout(L,Z)},b=async L=>{if(m.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>m.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}m.dirtyFields&&(r.dirtyFields=I0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:L0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=m.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(p),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await T2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!D0(q)):!D0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>G3(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Yd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,tP(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,Q3(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Gd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Xx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(m.isDirty||m.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:I0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),E2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?L0(me._f):B3(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=E2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return m.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=P2(r.errors,o,q),Ii=P2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await T2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:m.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||m.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?L0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(D0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(U3(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),m.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Kx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?I0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Gx({subject:i._subjects.state,next:s=>{H3(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=W3(r,i),t.current}var A2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},nP=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?A2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return A2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&nP(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(p){return p.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=X3(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&nP({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var M2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(M2||(M2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case he.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ce(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),O2=e=>e.status==="aborted",N2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const D2=(e,t)=>{if(Zp(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return D2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return D2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ug.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let F0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ce(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ce(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ce(n,{code:he.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,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ce(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const p=i[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new Qo(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of l)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")l.length>0&&(Ce(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of l){const m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new Qo(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key;f.push({key:m,value:await p.value,alwaysSet:p.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return rP(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ce(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ce(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class qx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ce(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ce(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new qx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(O2(i)||O2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((N2(i)||N2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ce(r,{code:he.invalid_intersection_types}),Ze)};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}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ce(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ce(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ce(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ce(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ce(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ce(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const p of u){if(p.status==="aborted")return Ze;p.status==="dirty"&&n.dirty(),f.add(p.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ce(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),p=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),m=await Reflect.apply(s,this,p);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw f.addIssue(o(m,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const p=Reflect.apply(s,this,f.data),m=l._def.returns.safeParse(p,i);if(!m.success)throw new Go([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ce(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function rP(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=rP;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ce(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ce(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ce(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ce(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ug extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new ug({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;qx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;ug.create;const L1="horizontal",mX=["horizontal","vertical"],oP=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=iP(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});oP.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!iP(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function iP(e){return mX.includes(e)}const sP=oP,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(sP,{ref:o,decorative:n,orientation:t,className:_e("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=sP.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),aP=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(aP,{ref:r,className:_e(yX(),e,t?"opacity-50":"","select-none"),...n}));Qx.displayName=aP.displayName;const wX=OY,lP=d.createContext({}),al=({...e})=>v.jsx(lP.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),dg=()=>{const e=d.useContext(lP),t=d.useContext(cP),{getFieldState:n,formState:r}=cg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},cP=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(cP.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:_e("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=dg();return v.jsx(Qx,{ref:n,className:_e(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=dg();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=dg();return v.jsx("p",{ref:n,id:r,className:_e("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=dg(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:_e("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const uP="Switch",[bX,_te]=Mn(uP),[SX,_X]=bX(uP),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=m?!!m.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":dP(E),"data-disabled":l?"":void 0,disabled:l,value:u},p,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":dP(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=Ux(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function dP(e){return e?"checked":"unchecked"}const fP=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(fP,{className:_e("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:_e("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=fP.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[hT]),zs=hT(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(zd,Y({},o,r,{ref:t}))}),hP="AlertDialogContent",[NX,DX]=PX(hP),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:hP,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Bd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var p;f.preventDefault(),(p=u.current)===null||p===void 0||p.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Ud,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,pP=OX,mP=IX,gP=zX,vP=UX,yP=FX,wP=jX,HX=VX,KX=WX,xP=d.forwardRef(({className:e,...t},n)=>v.jsx(pP,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));xP.displayName=pP.displayName;const bP=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(xP,{}),v.jsx(mP,{ref:n,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));bP.displayName=mP.displayName;const SP=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});SP.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(yP,{ref:n,className:_e("text-lg font-semibold",e),...t}));GX.displayName=yP.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(wP,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));YX.displayName=wP.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(gP,{ref:n,className:_e(_x(),e),...t}));XX.displayName=gP.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(vP,{ref:n,className:_e(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=vP.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),_P="General",F1="Model",EP="Plugins",QX=[F1,_P,EP];function JX(){const[e,t]=eT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=xt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:p}=Id(),[m,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:yk}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=m.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${m.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(m.name);p({title:`Switch to ${$e.name} success`}),u(m)}catch($e){p({variant:"destructive",title:`Switch to ${m.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await y0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await y0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await y0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,m,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:_e([ee.name===m.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(m.name===ee.name){M=ee.model_type,M===sC&&(M=ch),M===aC&&(M=uh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:m.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(l3,{defaultValue:M,children:[v.jsxs(Bx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:ch,children:"Stable Diffusion"}),v.jsx(pa,{value:uh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:f0,children:"Other Diffusion"})]}),v.jsxs(lg,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:ch,children:G([ch,sC])}),v.jsx(Su,{value:uh,children:G([uh,aC])}),v.jsx(Su,{value:f0,children:G([f0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(bP,{children:v.jsx(SP,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(eg,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Wd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Hd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:_e(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===_P?U():v.jsx(v.Fragment,{}),n===EP?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(eg,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Wd,{children:[v.jsx(Hd,{children:"Buy me a coffee"}),v.jsx(wT,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,p,m,g,y]=xt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{p()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:_e(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(Jk,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(NT,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},CP={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},$P=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&($P(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function RP(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return $P(e.animation);var s=new Date().getTime()-o,l=s/n,u=CP[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=t.scale-l,m=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):RP(e,r,n,function(y){var x=l+p*y,S=u+m*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,p=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:p}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,p=l,m=r-o-u,g=u;return{minPositionX:f,maxPositionX:p,minPositionY:m,maxPositionY:g}},Jx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,p=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,f,l,p,m,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=Jx(e,t);return e.bounds=n,n};function fg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,p=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=j1(e,l-m,f+m,r),x=j1(t,u-g,p+g,r);return{x:y,y:x}}function hg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var m=u-t*p,g=f-n*p,y=fg(m,g,o,i,0,0,null);return y}function Xd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var I2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=pg(i,n);return!u},L2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var p=e.bounds,m=p.maxPositionX,g=p.minPositionX,y=p.maxPositionY,x=p.minPositionY,S=n>m||ny||rm?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=hg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,p=u.positionX,m=u.positionY;if(!(s===null||l===null||t===p&&n===m)){var g=fg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var p=t-r.x,m=n-r.y,g=s?u:p,y=l?f:m;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function F2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var p=s+(e-s)*f;return p>u?u:pi?i:p}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),p=t.x-r.x,m=t.y-r.y,g=p/f,y=m/f,x=u-o,S=p*p+m*m,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,p=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=p-G,M=m+se,ee=g-se,H=e.transformState,X=new Date().getTime();RP(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=CP[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=F2(Me,H.positionX,$e,b,y,p,f,ne,U,xe),Mt=F2(Oe,H.positionY,Ve,_,y,g,m,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function j2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function kP(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,p=i||t.1&&m;g?AZ(e):kP(e)}}function eb(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Xd(Wr(t,2),i,s,0,!1),f=vc(e,u),p=hg(e,n,r,u,f,l),m=p.x,g=p.y;return{scale:u,positionX:m,positionY:g}}function TP(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,p=u.animationTime,m=u.animationType,g=f||r>=s;if((r>=1||l)&&kP(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=eb(e,s,y,x);S&&Bs(e,S,p,m)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=pg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},IP=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,p=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Xd(Wr(g,2),s,i,f,!p&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,p=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=m.size,E=m.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=DP(t,i,u),D=E||S===0||p||y,B=f&&D,V=hg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(TP(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=IP(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,p=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=IP(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||p===0||l,E=s&&S,_=hg(e,m.x,m.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,TP(e,t==null?void 0:t.x,t==null?void 0:t.y)},LP=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),OP(e,s,l,function(){return Nt(_t(e),t,o)}),LP(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,p=n.doubleClick,m=p.disabled,g=p.mode,y=p.step,x=p.animationTime,S=p.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=AP(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=DP(t,i,s),C=eb(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),LP(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),p=n&&u&&f&&!s;if(!p)return!1;var m=pg(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=U2(r)},this.initializeWindowEvents=function(){var r,o=z0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=z0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=z0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),j2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=L2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),z2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,p=u.length===2;f&&(jo(n),j2(n,r),Nt(_t(n),r,i)),p&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=L2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];z2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=NP(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=U2(this.props),this.transformState=PP(this.props)}return e}(),tb=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(tb.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(tb);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,V2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,p=e.contentProps,m=p===void 0?{}:p,g=d.useContext(tb),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(V2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},m,{ref:E,className:"react-transform-component ".concat(V2.content," ").concat(i),style:l}),t))};const FP=["PageUp","PageDown"],jP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zP={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Zd="Slider",[U1,gq,vq]=Kd(Zd),[BP,Cte]=Mn(Zd,[vq]),[yq,mg]=BP(Zd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:p,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:p,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),m(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=FP.includes(U.key)||U.shiftKey&&jP.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[UP,VP]=BP(Zd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||m.getBoundingClientRect(),P=[0,R.width],A=nb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(WP,Y({dir:S,"data-orientation":"horizontal"},p,{ref:y,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=zP[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,p=d.useRef(null),m=Ue(t,p),g=d.useRef(),y=!o;function x(S){const E=g.current||p.current.getBoundingClientRect(),_=[0,E.height],C=nb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(WP,Y({"data-orientation":"vertical"},f,{ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=zP[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),WP=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,p=mg(Zd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):FP.concat(jP).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),p.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),W2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(W2,n),i=VP(W2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>HP(g,o.min,o.max)),p=u>1?Math.min(...f):0,m=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:p+"%",[i.endEdge]:m+"%"}}))}),H2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=mg(H2,n),s=VP(H2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),p=yx(l),m=i.values[r],g=m===void 0?0:HP(m,i.min,i.max),y=Tq(r,i.values.length),x=p==null?void 0:p[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=Ux(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function HP(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=nb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function nb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const KP=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(KP,{ref:n,className:_e("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=KP.displayName;const ll={capture:!0,passive:!1},jq=2,K2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,p,{x:m,y:g,width:y,height:x},S,E,_,b,C,R]=xt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>K2(W,le,m,y,n,o),J=(W,le)=>K2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:_e(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!p?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=xt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=xt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,G2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:p,width:m,height:g},y,x,S,E,_,b,C]=xt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>G2(ee,H,f,n),D=(ee,H)=>G2(ee,H,p,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,m,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:_e(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),M=()=>v.jsx("div",{className:_e("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:f,top:p},children:[M(),ne(),se()]})})},Gq=200,Yq=3,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A,D]=xt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=xt(K=>K.editorState.baseBrushSize),V=xt(K=>K.getBrushSize()),J=xt(K=>K.editorState.renders),G=xt(K=>K.editorState.extraMasks),se=xt(K=>K.editorState.temporaryMasks),U=xt(K=>K.editorState.lineGroups),ne=xt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),ZR(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var ef;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&p(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((ef=q.current)==null||ef.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(h0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await wk(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(hC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},Sg=K=>{if(g.isInteractiveSeg){const Ye=h0(K),st=[...g.clicks];fC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},_g=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!fC(K)){if(hC(K)){ze(!0);return}ke(!0),x(h0(K))}},Qd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Qd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),l2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},Eg=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-3),m(K)},[B]),Zn("]",()=>{m(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),l2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},Jd=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Cg=K=>{m(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},$g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Rg=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:_e("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:Eg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:_g,onMouseUp:Sg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[Rg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?$g():Lc(Jd(Ve,We))),Re&&Lc(Jd(L,Z)),v.jsxs("div",{className:"fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Cg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Qd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=xt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],GP=["ArrowUp","PageDown","End"],Jq=[...Qq,...GP],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gg="Menu",[md,nQ,rQ]=Kd(gg),[za,YP]=Mn(gg,[rQ,Fs,ng]),vg=Fs(),XP=ng(),[ZP,Us]=za(gg),[oQ,qd]=za(gg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=vg(t),[u,f]=d.useState(null),p=d.useRef(!1),m=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{p.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>p.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(Fd,l,d.createElement(ZP,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:p,dir:g,modal:s},r)))},qP=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vg(n);return d.createElement(Wm,Y({},o,r,{ref:t}))}),QP="MenuPortal",[sQ,JP]=za(QP,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(QP,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,rb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(ob,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(ob,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),ob=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=qd(bo,n),b=vg(n),C=XP(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?Qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Zm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Xm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y},d.createElement(JT,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Hm,Y({role:"menu","aria-orientation":"vertical","data-state":iA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);GP.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",Y2="menu.itemSelect",ib=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=qd(W1,e.__scopeMenu),l=rb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),p=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(Y2,{bubbles:!0,cancelable:!0});m.addEventListener(Y2,y=>r==null?void 0:r(y),{once:!0}),dx(m,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(eA,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,p),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),f.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;f.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||V1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),eA=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=rb(W1,n),l=XP(n),u=d.useRef(null),f=Ue(t,u),[p,m]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(e3,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(nA,{scope:e.__scopeMenu,checked:n},d.createElement(ib,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":sb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(nA,{scope:e.__scopeMenu,checked:i},d.createElement(ib,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":sb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),tA="MenuItemIndicator",[nA,yQ]=za(tA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(tA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":sb(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),rA="MenuSub",[bQ,oA]=za(rA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(rA,t),s=vg(t),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ft(o);return d.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),d.createElement(Fd,s,d.createElement(ZP,{scope:t,open:r,onOpenChange:m,content:f,onContentChange:p},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},Sh="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(Sh,e.__scopeMenu),r=qd(Sh,e.__scopeMenu),o=oA(Sh,e.__scopeMenu),i=rb(Sh,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},p=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>p,[p]),d.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),d.createElement(qP,Y({asChild:!0},f),d.createElement(eA,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":iA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(m=>{var g;p();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+_,y:m.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu),l=oA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(ob,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:ue(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,p=>{s.onClose(),p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{const m=p.currentTarget.contains(p.target),g=tQ[s.dir].includes(p.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),p.preventDefault()}})})))))});function iA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function sb(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=qP,OQ=aQ,NQ=cQ,DQ=fQ,IQ=ib,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,sA="DropdownMenu",[WQ,Rte]=Mn(sA,[YP]),_r=YP(),[HQ,aA]=WQ(sA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[p=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:p,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(g=>!g),[m]),modal:l},d.createElement(AQ,Y({},u,{open:p,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=aA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({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:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=aA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,p=u.button===2||f;(!o.modal||p)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,lA=qQ,cA=QQ,uA=JQ,dA=eJ,fA=tJ,hA=nJ,pA=rJ,uJ=oJ,mA=iJ,gA=sJ,dJ=aJ,fJ=lJ,X2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(mA,{ref:o,className:_e("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=mA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(gA,{ref:n,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=gA.displayName;const vA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(lA,{ref:r,sideOffset:t,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));vA.displayName=lA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(uA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=uA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(dA,{ref:o,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(xk,{className:"h-4 w-4"})})}),t]}));hJ.displayName=dA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(fA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=fA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:_e("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=cA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(pA,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=pA.displayName;const Z2={RemoveBG:{IconClass:GC,showName:"RemoveBG"},AnimeSeg:{IconClass:GC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:Qk,showName:"RealESRGAN"},GFPGAN:{IconClass:YC,showName:"GFPGAN"},RestoreFormer:{IconClass:YC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r,o]=xt(p=>[p.file,p.serverConfig.plugins,p.isPluginRunning,p.updateInteractiveSegState,p.runRenderablePlugin]),i=!e;if(t.length===0)return null;const s=(p,m)=>{m==="InteractiveSeg"?r({isInteractiveSeg:!0}):o(p,m)},l=()=>v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(Qk,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),u=p=>{const{IconClass:m,showName:g}=Z2[p.name];return v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>s(!1,p.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>s(!0,p.name),children:"Generate Mask"})]})]},p.name)},f=()=>t.map(p=>{const{IconClass:m,showName:g}=Z2[p.name];return p.name==="RealESRGAN"?l():p.name==="RemoveBG"||p.name==="AnimeSeg"?u(p):v.jsx(fl,{onClick:()=>s(!1,p.name),disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})},p.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:n?v.jsx("div",{role:"status",children:v.jsxs("svg",{"aria-hidden":"true",className:"w-5 h-5 animate-spin fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]})}):v.jsx(KU,{strokeWidth:1})})}),v.jsx(vA,{side:"bottom",align:"start",children:f()})]})},yJ=Cx,wJ=xT,xJ=$x,yA=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{className:_e("fixed inset-0 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));yA.displayName=zd.displayName;const bJ=Dm("fixed gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),wA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(yA,{}),v.jsx(Bd,{ref:o,className:_e(bJ({side:e}),t),...r,children:n})]}));wA.displayName=Bd.displayName;const xA=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});xA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Ud.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));_J.displayName=Vd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(Qx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=xt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},_h=({text:e,onClick:t})=>{const[n]=xt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,p]=xt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[m,g]=Px(n),y=d.useRef(null);DT(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(Dx,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==XR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(Jk,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(_h,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(_h,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(_h,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(_h,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:p,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=xt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=xt(i=>[i.settings,i.windowSize]),[n,r]=Nx(!0);if(Zn("c",()=>{r()}),e.model.name!==lC&&e.model.name!==cC&&e.model.model_type===fs)return null;const o=()=>e.model.name===lC?v.jsx(EJ,{}):e.model.name===cC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",hidden:n,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(wA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(xA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(lg,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ab=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):q2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):q2(new Blob([t]),r):r(Jo[e]+(t||"")),q2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Q2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let B0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Q2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Q2(e.data));ab(e,!1,n=>{B0||(B0=new TextEncoder),t(B0.encode(n))})}const J2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),p=new Uint8Array(f);for(r=0;r>4,p[o++]=(s&15)<<4|l>>2,p[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",lb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ab(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let U0;function Eh(e){return e.reduce((t,n)=>t+n.length,0)}function Ch(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=p*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Eh(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function yg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=n$(+new Date);return e!==t$?(e$=0,t$=e):e+"."+n$(e$++)}for(;$h{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=TA()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Xo extends qt{constructor(t,n){super(),yg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",r$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,r$,!1)}}function r$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const ub=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Rh=Br.WebSocket||Br.MozWebSocket,o$=!0,ZJ="arraybuffer",i$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends cb{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=i$?{}:RA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=o$&&!i$?n?new Rh(t,n):new Rh(t):new Rh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{o$&&this.ws.send(i)}catch{}o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!Rh}}class QJ extends cb{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=X1(n.host).host),yg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=$A,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,p(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(m){n&&m.name!==n.name&&i()}const p=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){hl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function db(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ac.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,yg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ub(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new NA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",wg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:wg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:wg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${wg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:_e("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=xt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=xt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[hb,Aee,Mee]=Kd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,xg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,p]=d.useState(0),m=d.useRef(!1),g=d.useRef(!1);return d.createElement(hb.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>p(y=>y+1),[]),onToastRemove:d.useCallback(()=>p(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=xg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),p=d.useRef(null),m=d.useRef(null),g=Ue(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=m.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=m.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(V0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=p.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(a$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});V0(E)}}),d.createElement(hb.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(a$,{ref:p,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});V0(E)}}))}),Lee="ToastFocusProxy",a$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=xg(Lee,n);return d.createElement(Km,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),bg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=UA(bg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:p,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=xg(bg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(hb.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,kh(jee,m,Ve,{discrete:!1})):l$($e,S.swipeDirection,pe)?(R.current=$e,kh(Fee,p,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};l$(ne,S.swipeDirection,S.swipeThreshold)?kh(Bee,y,H,{discrete:!0}):kh(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${bg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=xg(bg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(jd,{asChild:!0},d.createElement(Km,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function kh(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const l$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function V0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,e6=KA,ete=Jee,t6=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:_e("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));t6.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),n6=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:_e(tte({variant:t}),e),tabIndex:-1,...n}));n6.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:_e("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const r6=d.forwardRef(({className:e,...t},n)=>v.jsx(e6,{ref:n,className:_e("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(bk,{className:"h-4 w-4"})}));r6.displayName=e6.displayName;const o6=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:_e("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));o6.displayName=qA.displayName;const i6=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:_e("text-sm opacity-90",e),...t,tabIndex:-1}));i6.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(n6,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(o6,{children:n}),r&&v.jsx(i6,{children:r})]}),o,v.jsx(r6,{})]},t)}),v.jsx(t6,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=xt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await yk();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),p=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",p),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",p),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],pb="(prefers-color-scheme: dark)",ste=typeof window>"u",s6=d.createContext(void 0),ate=e=>d.useContext(s6)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:p})=>{const[m,g]=d.useState(()=>c$(o,s)),[y,x]=d.useState(()=>c$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=u$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=u$(R);x(P),m==="system"&&n&&!e&&E("system")},[m,e]);d.useEffect(()=>{const R=window.matchMedia(pb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??m)},[e,m]);const C=d.useMemo(()=>({theme:m,setTheme:_,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,_,e,y,n,i]);return je.createElement(s6.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:p}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",p=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${p}${g(e)}}()`:r?`!function(){try{${p}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${pb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${p}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),c$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},u$=e=>(e||(e=window.matchMedia(pb)),e.matches?"dark":"light"),fte=new pL;W0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-TI-UMrGI.js b/py/iopaint/web_app/assets/index-TI-UMrGI.js new file mode 100644 index 0000000..14a546a --- /dev/null +++ b/py/iopaint/web_app/assets/index-TI-UMrGI.js @@ -0,0 +1,165 @@ +var Fv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Fv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Fv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Wf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Fv(e,t,"access private method"),n);function $9(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var x$={exports:{}},fm={},b$={exports:{}},it={};/** + * @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. + */var kd=Symbol.for("react.element"),R9=Symbol.for("react.portal"),k9=Symbol.for("react.fragment"),T9=Symbol.for("react.strict_mode"),P9=Symbol.for("react.profiler"),A9=Symbol.for("react.provider"),M9=Symbol.for("react.context"),O9=Symbol.for("react.forward_ref"),N9=Symbol.for("react.suspense"),D9=Symbol.for("react.memo"),I9=Symbol.for("react.lazy"),B_=Symbol.iterator;function L9(e){return e===null||typeof e!="object"?null:(e=B_&&e[B_]||e["@@iterator"],typeof e=="function"?e:null)}var S$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_$=Object.assign,E$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}yc.prototype.isReactComponent={};yc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function C$(){}C$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=E$,this.updater=n||S$}var rw=nw.prototype=new C$;rw.constructor=nw;_$(rw,yc.prototype);rw.isPureReactComponent=!0;var U_=Array.isArray,$$=Object.prototype.hasOwnProperty,ow={current:null},R$={key:!0,ref:!0,__self:!0,__source:!0};function k$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)$$.call(t,r)&&!R$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],p=1,m=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),m=n(u);m!==null&&(!(m.expirationTime>X)||H&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var pe=le(m.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?m.callback=pe:m===n(u)&&r(u),C(X)}else r(u);m=n(u)}if(m!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{m=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(M$);A$.exports=M$;var X9=A$.exports;/** + * @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. + */var O$=d,yr=X9;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),H0=Object.prototype.hasOwnProperty,Z9=/^[: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]*$/,W_={},H_={};function q9(e){return H0.call(H_,e)?!0:H0.call(W_,e)?!1:Z9.test(e)?H_[e]=!0:(W_[e]=!0,!1)}function Q9(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function J9(e,t,n,r){if(t===null||typeof t>"u"||Q9(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(e,2,!1,e,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(e){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(e){return e[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(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Bv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function eD(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Uv(e.type,!1),e;case 11:return e=Uv(e.type.render,!1),e;case 1:return e=Uv(e.type,!0),e;default:return""}}function X0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case pl:return"Portal";case K0:return"Profiler";case cw:return"StrictMode";case G0:return"Suspense";case Y0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case I$:return(e.displayName||"Context")+".Consumer";case D$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:X0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return X0(e(t))}catch{}}return null}function tD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return X0(t);case 8:return t===cw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function F$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function nD(e){var t=F$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Gf(e){e._valueTracker||(e._valueTracker=nD(e))}function j$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=F$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Z0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function G_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function z$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function q0(e,t){z$(e,t);var n=Rs(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&Q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Y_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Yf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},rD=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){rD.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function W$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function H$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=W$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var oD=zt({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 ty(e,t){if(t){if(oD[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ny(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 ry=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var oy=null,kl=null,Tl=null;function q_(e){if(e=Ad(e)){if(typeof oy!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),oy(e.stateNode,e.type,t))}}function K$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function G$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,q_(e),t)for(e=0;e>>=0,e===0?32:31-(mD(e)/gD|0)|0}var Xf=64,Zf=4194304;function wu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function xD(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=$u),sE=" ",aE=!1;function h5(e,t){switch(e){case"keyup":return YD.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function p5(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function ZD(e,t){switch(e){case"compositionend":return p5(t);case"keypress":return t.which!==32?null:(aE=!0,sE);case"textInput":return e=t.data,e===sE&&aE?null:e;default:return null}}function qD(e,t){if(gl)return e==="compositionend"||!xw&&h5(e,t)?(e=d5(),Mh=vw=us=null,gl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=dE(n)}}function y5(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?y5(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function w5(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sI(e){var t=w5(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&y5(n.ownerDocument.documentElement,n)){if(r!==null&&bw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=fE(n,i);var s=fE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vl=null,uy=null,ku=null,dy=!1;function hE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;dy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(uy,"onSelect"),0xl||(e.current=vy[xl],vy[xl]=null,xl--)}function $t(e,t){xl++,vy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function xE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function k5(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,tD(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function bE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=k5(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,n0=!1;function T5(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,T5(e)}function Ds(){if(!n0&&pi!==null){n0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=m(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Kf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&kE(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=zh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=u0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);rh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=c0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=L5(!0),F5=L5(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:ey(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=ey(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function j5(e){fa(Zu.current);var t=fa(Ko.current),n=ey(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var r0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=o0.transition;o0.transition={};try{e(!1),t()}finally{xt=n,o0.transition=r}}function tR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},nR(e))rR(t,n);else if(n=O5(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),oR(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(nR(e))rR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=O5(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),oR(n,t,r))}}function nR(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function rR(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function oR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:PE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Ih(4194308,4,Z5.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ih(4194308,4,e,t)},useInsertionEffect:function(e,t){return Ih(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:TE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=TE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||U5(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,PE(W5.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,V5.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Io]=t,e[Yu]=r,hR(e,t,!1,!1),t.stateNode=e;e:{switch(s=ny(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var ih=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,Ee=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Ty(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var jE=!1;function NI(e,t){if(fy=fp,e=w5(),bw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,f=0,p=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++p===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(hy={focusedElem:e,selectionRange:n},fp=!1,Ee=t;Ee!==null;)if(t=Ee,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Ee=e;else for(;Ee!==null;){t=Ee;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,Ee=e;break}Ee=t.return}return x=jE,jE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Ty(t,n,i)}o=o.next}while(o!==r)}}function bm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Py(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function gR(e){var t=e.alternate;t!==null&&(e.alternate=null,gR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[gy],delete t[gI],delete t[vI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function vR(e){return e.tag===5||e.tag===3||e.tag===4}function zE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||vR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ay(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mp));else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}function My(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(My(e,t,n),e=e.sibling;e!==null;)My(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)yR(e,t,n),n=n.sibling}function yR(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?t0(e.parentNode,n):e.nodeType===1&&t0(e,n),Vu(e)):t0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(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||i&4)&&Ty(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function BE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Ee=e.current;Ee!==null;){var i=Ee,s=i.child;if(Ee.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function $R(e,t){t===0&&(e.mode&1?(t=Zf,Zf<<=1,!(Zf&130023424)&&(Zf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$R(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),$R(e,n)}var RR;RR=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&P5(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Lh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,Sy(t,r,e,n),t=Cy(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Lh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=Ey(null,t,r,e,n);break e;case 1:t=IE(null,t,r,e,n);break e;case 11:t=NE(null,t,r,e,n);break e;case 14:t=DE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ey(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),IE(e,t,r,o,n);case 3:e:{if(uR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,N5(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=LE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=LE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=F5(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return j5(t),e===null&&wy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,py(r,o)?s=null:i!==null&&py(r,i)&&(t.flags|=32),cR(e,t),In(e,t,s,n),t.child;case 6:return e===null&&wy(t),null;case 13:return dR(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var p=f.pending;p===null?u.next=u:(u.next=p.next,p.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),xy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),xy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),DE(e,t,r,o,n);case 15:return aR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Lh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),I5(t,r,o),Sy(t,r,o,n),Cy(null,t,r,!0,e,n);case 19:return fR(e,t,n);case 22:return lR(e,t,n)}throw Error(ce(156,t.tag))};function kR(e,t){return e5(e,t)}function WI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function zh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case K0:return e=Ur(12,n,t,o|2),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(13,n,t,o),e.elementType=G0,e.lanes=i,e;case Y0:return e=Ur(19,n,t,o),e.elementType=Y0,e.lanes=i,e;case L$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case D$:s=10;break e;case I$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=L$,e.lanes=n,e.stateNode={isHidden:!1},e}function c0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function u0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Wv(0),this.expirationTimes=Wv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Wv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(MR)}catch(e){console.error(e)}}MR(),P$.exports=br;var Is=P$.exports;const QI=dm(Is);var XE=Is;W0.createRoot=XE.createRoot,W0.hydrateRoot=XE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Ly(e){return typeof e=="number"&&e>=0&&e!==1/0}function OR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function ZE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function qE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>jy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function NR(e,t){if(e===t)return e;const n=QE(e)&&QE(t);if(n||jy(e)&&jy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!JE(n)||!n.hasOwnProperty("isPrototypeOf"))}function JE(e){return Object.prototype.toString.call(e)==="[object Object]"}function DR(e){return new Promise(t=>{setTimeout(t,e)})}function eC(e){DR(0).then(e)}function zy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?NR(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,d$,nL=(d$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,d$),Ap=new nL,Ll,os,Fl,f$,rL=(f$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,f$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var IR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function d0(e){return e instanceof IR}function LR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new IR(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},p=()=>{t=!1},m=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!m();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:p}}function iL(){let e=[],t=0,n=p=>{p()},r=p=>{p()};const o=p=>{let m;t++;try{m=p()}finally{t--,t||l()}return m},i=p=>{t?e.push(p):eC(()=>{n(p)})},s=p=>(...m)=>{i(()=>{p(...m)})},l=()=>{const p=e;e=[],p.length&&eC(()=>{r(()=>{p.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:p=>{n=p},setBatchNotifyFunction:p=>{r=p}}}var vn=iL(),va,h$,FR=(h$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Ly(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,h$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Bh,ao,di,p$,sL=(p$=class extends FR{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Bh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=zy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!OR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,p,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Bh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Bh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(p=this.options.behavior)==null||p.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;d0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),d0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,LR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Bh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return d0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},p$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,m$,lL=(m$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>ZE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>ZE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,m$),Oo,yd,dr,Ul,No,qi,g$,cL=(g$=class extends FR{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,LR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((m=(p=this.options).onSuccess)==null?void 0:m.call(p,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},g$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,v$,dL=(v$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Wf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>qE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>qE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,v$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const p=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};p(O);const A=await m(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:tC,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function tC(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,y$,pL=(y$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Wf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Wf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,y$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,By,Sd,Uy,_d,Vy,Ed,Wy,Cd,Hy,$d,Ky,Rd,Gy,um,jR,w$,mL=(w$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),nC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Wy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Yy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Yy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Hy).call(this),tt(this,$d,Ky).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Fy(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Gy).call(this);const i=this.hasListeners();i&&rC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,By).call(this);const s=tt(this,Sd,Uy).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Vy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:p}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=p,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&nC(t,n),B=A&&rC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",p.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof p.data<"u")if(i&&p.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(p.data),E=zy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=p.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=zy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(m=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:p.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:p.fetchFailureCount,failureReason:p.fetchFailureReason,errorUpdateCount:p.errorUpdateCount,isFetched:p.dataUpdateCount>0||p.errorUpdateCount>0,isFetchedAfterMount:p.dataUpdateCount>f.dataUpdateCount||p.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&p.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&p.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Fy(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const p=f;return j(this,kn)[p]!==n[p]&&u.has(p)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,jR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Wy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Gy).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,By=function(){if(tt(this,Cd,Hy).call(this),oc||j(this,kn).isStale||!Ly(this.options.staleTime))return;const n=OR(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,Uy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Vy=function(t){tt(this,$d,Ky).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Ly(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Wy=function(){tt(this,bd,By).call(this),tt(this,_d,Vy).call(this,tt(this,Sd,Uy).call(this))},Cd=new WeakSet,Hy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Ky=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Gy=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,jR=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},w$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function nC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Yy(e,t,t.refetchOnMount)}function Yy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function rC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Fy(e.getCurrentResult(),t)}var zR=d.createContext(void 0),yL=e=>{const t=d.useContext(zR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(zR.Provider,{value:e},t)),BR=d.createContext(!1),xL=()=>d.useContext(BR);BR.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const p=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),p},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function UR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const oC=/^\[(.+)\]$/;function NL(e){if(oC.test(e)){const t=oC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Xy(s,r,i,t)}),r}function Xy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:iC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Xy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Xy(s,iC(t,i),n,r)})})}function iC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const HR="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,p;for(let S=0;Sf?p-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:p}=n(s);let m=r(p?f.substring(0,p):f),g=!!p;if(!m){if(!p)return{isTailwindClass:!1,originalClassName:s};if(m=r(f),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+HR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,p=l+u;return i.has(p)?!1:(i.add(p),o(u,f).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;em(p),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const p=VL(u,n);return o(u,p),p}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const GR=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\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$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function lh(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return GR.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,YR)}function tF(e){return bc(e,"position",YR)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=GR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function YR(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),p=kt("hueRotate"),m=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,lh],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",lh]}],"font-family":[{font:[cu]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,lh]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[p]}],invert:[{invert:[m]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[p]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,lh]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const tx=HL(lF),cF=40,fs="inpaint",ch="diffusers_sd",sC="diffusers_sdxl",uh="diffusers_sd_inpaint",aC="diffusers_sdxl_inpaint",f0="diffusers_other",Uh="#ffcc00bb",lC="ldm",cC="cv2",XR="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function _e(...e){return tx(VR(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function uC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function dC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function fC(e){return e.nativeEvent.button===2}function hC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function h0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function ZR(e,t,n=Uh){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{ZR(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function qR(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const QR=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&QR(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),JR=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const tk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,nk=e=>!rd(e)&&e!==tk;function Zy(){const{caseless:e}=nk(this)&&this||{},t={},n=(r,o)=>{const i=e&&ek(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=qR(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!JR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),pC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),rk=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{rk(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),p0="abcdefghijklmnopqrstuvwxyz",mC="0123456789",ok={DIGIT:mC,ALPHA:p0,ALPHA_DIGIT:p0+p0.toUpperCase()+mC},qF=(e=16,t=ok.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:QR,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:JR,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:pC,hasOwnProp:pC,reduceDescriptors:rk,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:ek,global:tk,isContextDefined:nk,ALPHABET:ok,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const ik=ut.prototype,sk={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{sk[e]={value:e}});Object.defineProperties(ut,sk);Object.defineProperty(ik,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(ik);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function ak(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function gC(e,t,n){return e?e.concat(t).map(function(o,i){return o=ak(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||p,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function p(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=ak(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?gC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(gC(E,S,i),f(x)),!1)}const m=[],g=Object.assign(oj,{defaultVisitor:p,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));m.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),m.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function vC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const lk=rx.prototype;lk.append=function(t,n){this._pairs.push([t,n])};lk.toString=function(t){const n=t?function(r){return t.call(this,r,vC)}:vC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function ck(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const yC=sj,uk={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},dk=typeof window<"u"&&typeof document<"u",dj=(e=>dk&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:dk,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:uk,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(fk(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},wC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function m0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const p=uu(u);if(!p)throw new Error("header name must be a non-empty string");const m=ie.findKey(o,p);(!m||o[m]===void 0||f===!0||f===void 0&&o[m]!==!1)&&(o[m||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,p)=>i(f,p,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||m0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||m0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||m0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[wC]=this[wC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function g0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function hk(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function pk(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),p=r[i];s||(s=f),n[o]=u,r[o]=f;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const p={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};p[t?"download":"upload"]=!0,e(p)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let p;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((p=i.getContentType())!==!1){const[S,...E]=p?p.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=pk(e.baseURL,e.url);m.open(e.method.toUpperCase(),ck(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const S=xi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:S,config:e,request:m};Ej(function(C){n(C),f()},function(C){r(C),f()},_),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||uk;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&ie.forEach(i.toJSON(),function(E,_){m.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",xC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",xC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{m&&(r(!S||S.type?new Dd(null,e,m):S),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const bC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,mk={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(bC).join(` +`):" "+bC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function v0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function SC(e){return v0(e),e.headers=xi.from(e.headers),e.data=g0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),mk.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return v0(e),r.data=g0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return hk(r)||(v0(e),r&&r.response&&(r.response.data=g0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const _C=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,p,m){return ie.isPlainObject(f)&&ie.isPlainObject(p)?ie.merge.call({caseless:m},f,p):ie.isPlainObject(p)?ie.merge({},p):ie.isArray(p)?p.slice():p}function o(f,p,m){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f,m)}else return r(f,p,m)}function i(f,p){if(!ie.isUndefined(p))return r(void 0,p)}function s(f,p){if(ie.isUndefined(p)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,p)}function l(f,p,m){if(m in t)return r(f,p);if(m in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,p)=>o(_C(f),_C(p),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(p){const m=u[p]||o,g=m(e[p],t[p],p);ie.isUndefined(g)&&m!==l||(n[p]=g)}),n}const gk="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const EC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+gk+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!EC[s]&&(EC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new yC,response:new yC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let p,m=0,g;if(!u){const x=[SC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,p=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function vk(e){const t=new Gh(e),n=qR(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return vk(ic(e,o))},n}const Qt=vk(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=hk;Qt.VERSION=gk;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>fk(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=mk.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const m=await f.blob();return{blob:URL.createObjectURL(m),seed:f.headers.get("X-Seed")}}const p=await f.json();throw new Error(`Something went wrong: ${p.errors}`)}async function yk(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function y0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function wk(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],xk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],bk=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const CC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,$C=VR,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const p=n==null?void 0:n[f],m=i==null?void 0:i[f];if(p===null)return null;const g=CC(p)||CC(m);return o[f][g]}),l=n&&Object.entries(n).reduce((f,p)=>{let[m,g]=p;return g===void 0||(f[m]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,p)=>{let{class:m,className:g,...y}=p;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,m,g]:f},[]);return $C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const p=od(i.serialize),m=()=>{const E=i.partialize({...r()});let _;const b=p({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),m()};const y=e((...E)=>{n(...E),m()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),m()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const p=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},m=o.setState;o.setState=(S,E)=>{m(S,E),p()};const g=e((...S)=>{n(...S),p()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),p()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Ek(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&_k(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function Ck(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function kC(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function TC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function PC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==Sk?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>AC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>AC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function AC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(Ek(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:Ck(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===w0(e.base_,t)?(x0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=$k(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=w0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;x0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return w0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,x0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function w0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=$k(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function $k(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function x0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,p=>n.call(this,p,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=TC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return kC(i,r),PC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===Sk&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=TC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return kC(r,t),PC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:Ck()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),Rk(e)}function Rk(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{Ek(n,r,Rk(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var kk={exports:{}},Tk={},Pk={exports:{}},Ak={};/** + * @license React + * use-sync-external-store-shim.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. + */var lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,b0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return b0(o)&&i({inst:o}),e(function(){b0(o)&&i({inst:o})})},[e]),Vz(n),n}function b0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;Ak.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;Pk.exports=Ak;var Gz=Pk.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;Tk.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,p=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Zz(p,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(p=y,m=S)}var f=!1,p,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};kk.exports=Tk;var nB=kk.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const MC=e=>{let t;const n=new Set,r=(u,f)=>{const p=typeof u=="function"?u(t):u;if(!Object.is(p,t)){const m=t;t=f??typeof p!="object"?p:Object.assign({},t,p),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?MC(e):MC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const OC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?OC(e,t):OC,uB=1,dB=1e6;let S0=0;function fB(){return S0=(S0+1)%Number.MAX_VALUE,S0.toString()}const _0=new Map,NC=e=>{if(_0.has(e))return;const t=setTimeout(()=>{_0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);_0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?NC(n):e.toasts.forEach(r=>{NC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M SDE Karras"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Uh);try{const f=await dC(u);e(p=>{p.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:p,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=m.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=p,_=x):(b=m,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_,Uh);if(E){const O=await dC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,uC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await wk(n,r,u,o.upscale),{blob:p}=f;if(n){const y=new Image;await Vh(y,p),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,p),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==XR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:p}=t();switch(l=f,u=p,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(p*(r-1)/2),u=Math.ceil(p*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(p*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(p*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Uh),f=uC(u.toDataURL()),p=await Gj(f,n,l),m=await mF(p);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Bm=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:_e("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Bm.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let p=u.target.value;if(t){if(p=p.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),p.length===0){n(0);return}n(parseFloat(p))}else{if(p=p.replace(/\D/g,""),p.length===0){n(0);return}n(parseInt(p,10))}s(p)};return v.jsx(Bm,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(m){const{scope:g,children:y,...x}=m,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function p(m,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,p]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const m=u(i)[`__scope${f}`];return{...l,...m}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let DC;const Mk=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,p=d.useContext(Mk),[m,g]=d.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(p.layers),[_]=[...p.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=m?E.indexOf(m):-1,R=p.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...p.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...p.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===p.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(m)return r&&(p.layersWithOutsidePointerEventsDisabled.size===0&&(DC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),p.layersWithOutsidePointerEventsDisabled.add(m)),p.layers.add(m),IC(),()=>{r&&p.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=DC)}},[m,y,r,p]),d.useEffect(()=>()=>{m&&(p.layers.delete(m),p.layersWithOutsidePointerEventsDisabled.delete(m),IC())},[m,p]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(Mk),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let p=function(){Ok(yB,n,f,{discrete:!0})};var u=p;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=p,t.addEventListener("click",o.current,{once:!0})):p()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&Ok(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function IC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function Ok(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=U9.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,dh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function Nk(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function LC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",p=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:p,y:r.y-o.height};break;case"bottom":y={x:p,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:p,y:m}=LC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:p=0}=Ci(e,t)||{};if(f==null)return{};const m=Nk(p),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(m[_],B),J=Ts(m[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function jC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function zC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=jC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:zC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=jC(i,n.floating);return{data:{escapedOffsets:s,escaped:zC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,p=i&&u?-1:1,m=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*p,y:g*f}:{x:g*f,y:y*p}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},p=await ld(t,u),m=$c($i(o)),g=fx(m);let y=f[g],x=f[m];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+p[E],C=y-p[_];y=c1(b,y,C)}if(s){const E=m==="y"?"top":"left",_=m==="y"?"bottom":"right",b=x+p[E],C=x-p[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[m]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),p={x:n,y:r},m=$c(o),g=fx(m);let y=p[g],x=p[m];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[m]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[m])||0)+(R?0:E.crossAxis),O=i.reference[m]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[m])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[m]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),p=Cc(n),m=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=p===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=p==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(m){const O=g-u.left-u.right;R=p||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=p||b?Ts(E,O):O}if(b&&!p){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);m?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return Dk(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(Dk(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function Dk(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function BC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ld(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Um(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Um(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Vm(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||BC(e)&&e.host||Mi(e);return BC(t)?t.host:t}function Ik(e){const t=cc(e);return Um(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Ld(t)?t:Ik(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=Ik(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ld(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function Lk(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=Lk(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function Fk(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?Fk(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,p=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,p*=S.x,m*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:p,height:m,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Ld(i))&&(s=Vm(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function jk(e){return Na(Mi(e)).left+Vm(e).scrollLeft}function XB(e){const t=Mi(e),n=Vm(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+jk(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function UC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=Fk(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function zk(e,t){const n=cc(e);return n===t||!Ri(n)||Um(n)?!1:Xr(n).position==="fixed"||zk(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Um(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ld(s)&&!u&&zk(e,s))?r=r.filter(p=>p!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,p)=>{const m=UC(t,p,o);return f.top=hr(m.top,f.top),f.right=Ts(m.right,f.right),f.bottom=Ts(m.bottom,f.bottom),f.left=hr(m.left,f.left),f},UC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return Lk(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Ld(o))&&(l=Vm(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=jk(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function VC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function Bk(e,t){const n=vr(e);if(!qo(e))return n;let r=VC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=VC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||Bk,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:Bk,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:p,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=dh(p),x=dh(o.clientWidth-(f+m)),S=dh(o.clientHeight-(p+g)),E=dh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),p=o||i?[...f?cd(f):[],...cd(t)]:[];p.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const m=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{p.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?FC({element:r.current,padding:o}).fn(n):{}:r?FC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!jp(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function Uk(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function WC(e,t){const n=Uk(e);return Math.round(t*n)/n}function HC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[p,m]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(p),B=HC(u),V=HC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{m(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,m(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=WC(U.floating,p.x),H=WC(U.floating,p.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...Uk(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,p.x,p.y]);return d.useMemo(()=>({...p,update:J,refs:se,elements:U,floatingStyles:ne}),[p,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Vk="Popper",[Wk,Fs]=Mn(Vk),[uU,Hk]=Wk(Vk),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=Hk(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),Kk="PopperContent",[pU,pte]=Wk(Kk),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:p,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=Hk(Kk,p),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=m+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=Gk(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:p,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,m=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,S]=Gk(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=m?E:`${_}px`,R=`${-y}px`):x==="top"?(C=m?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=m?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=m?E:`${b}px`),{data:{x:C,y:R}}}});function Gk(e){const[t,n="center"]=e.split("-");return[t,n]}const Fd=dU,Wm=hU,Hm=mU,jd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=fh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,p=o.current;if(p!==e){const g=i.current,y=fh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(p&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=m=>{const y=fh(r.current).includes(m.animationName);m.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},p=m=>{m.target===t&&(i.current=fh(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function fh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const m=typeof f=="function"?f(e):f;m!==e&&l(m)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Km=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Km,[Gm,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Gm(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const p=f.current;return()=>window.clearTimeout(p)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(p=>{u.current=p},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Ym]=Gm(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[p,m]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(Fd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:p,onTriggerChange:m,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},KC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Ym(KC,n),i=xx(KC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),p=d.useRef(!1),m=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),d.createElement(Wm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!p.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),p.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),p.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Gm(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Ym(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(Yk,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Ym(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,p=o.current,{onPointerInTransitChange:m}=r,g=d.useCallback(()=>{l(null),m(!1)},[m]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),m(!0)},[m]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&p){const x=E=>y(E,p),S=E=>y(E,u);return u.addEventListener("pointerleave",x),p.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),p.removeEventListener("pointerleave",S)}}},[u,p,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(p==null?void 0:p.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,p,s,f,g]),d.createElement(Yk,Y({},e,{ref:i}))}),[OU,vte]=Gm(bx,{isInside:!1}),Yk=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Ym(ud,n),f=wx(n),{onClose:p}=u;return d.useEffect(()=>(document.addEventListener(d1,p),()=>document.removeEventListener(d1,p)),[p]),d.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&p()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,p]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:p},d.createElement(Hm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.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)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,Xk=AU,VU=zU,Zk=BU,qk=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(Xk,{ref:r,sideOffset:t,className:_e("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=Xk.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:_e(_x({variant:t,size:n,className:e}),"outline-none cursor-default select-none"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Bm,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={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"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([p,m])=>d.createElement(p,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("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"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),Qk=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("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"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("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"}]]),sV=Jt("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"}]]),GC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),YC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),Jk=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function eT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const E0="focusScope.autoFocusOnMount",C0="focusScope.autoFocusOnUnmount",XC={bubbles:!1,cancelable:!0},Xm=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),p=Ft(i),m=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?m.current=A:Qi(m.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(m.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){qC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(E0,XC);l.addEventListener(E0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(tT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(E0,f),setTimeout(()=>{const _=new CustomEvent(C0,XC);l.addEventListener(C0,p),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(C0,p),qC.remove(y)},0)}}},[l,f,p,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=tT(e),n=ZC(t,e),r=ZC(t.reverse(),e);return[n,r]}function tT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function ZC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const qC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=QC(e,t),e.unshift(t)},remove(t){var n;e=QC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function QC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let $0=0;function Zm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:JC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:JC()),$0++,()=>{$0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),$0--}},[])}function JC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=iT(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var hh=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",hh,hh),window.removeEventListener("test",hh,hh)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},sT=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return sT(e,"overflowY")},jV=function(e){return sT(e,"overflowX")},t2=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=aT(e,n);if(r){var o=lT(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},aT=function(e,t){return e==="v"?FV(t):jV(t)},lT=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,p=s>0,m=0,g=0;do{var y=lT(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&aT(e,l)&&(m+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(p&&(o&&m===0||!o&&s>m)||!p&&(o&&g===0||!o&&-s>g))&&(f=!0),f},ph=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},n2=function(e){return[e.deltaX,e.deltaY]},r2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return iT()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(r2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=ph(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=t2(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=t2(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?n2(E):ph(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(r2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),p=d.useCallback(function(S){n.current=ph(S),r.current=void 0},[]),m=d.useCallback(function(S){f(S.type,n2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,ph(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",p,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",p,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(oT,GV);var cT=d.forwardRef(function(e,t){return d.createElement(qm,Lo({},e,{ref:t,sideCar:YV}))});cT.classNames=qm.classNames;const Qm=cT;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,mh=new WeakMap,gh={},T0=0,uT=function(e){return e&&(e.host||uT(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=uT(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);gh[n]||(gh[n]=new WeakMap);var i=gh[n],s=[],l=new Set,u=new Set(o),f=function(m){!m||l.has(m)||(l.add(m),f(m.parentNode))};o.forEach(f);var p=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))p(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&mh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return p(t),l.clear(),T0++,function(){s.forEach(function(m){var g=il.get(m)-1,y=i.get(m)-1;il.set(m,g),i.set(m,y),g||(mh.has(m)||m.removeAttribute(r),mh.delete(m)),y||m.removeAttribute(n)}),T0--,T0||(il=new WeakMap,il=new WeakMap,mh=new WeakMap,gh={})}},Jm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const dT="Dialog",[fT,hT]=Mn(dT),[QV,Eo]=fT(dT),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,p]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(m=>!m),[p]),modal:s},n)},eW="DialogTrigger",pT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),mT="DialogPortal",[tW,gT]=fT(mT,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(mT,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=gT(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(Qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=gT(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(vT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(vT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),vT=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Zm(),d.createElement(d.Fragment,null,d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),yT="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(yT,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",wT=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:yT,docsSlug:"dialog"}),Cx=JV,xT=pT,$x=nW,zd=rW,Bd=iW,Ud=lW,Vd=wT,Rx=dW,eg=Cx,kx=xT,pW=$x,bT=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{ref:n,className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));bT.displayName=zd.displayName;const Wd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(bT,{}),v.jsxs(Bd,{ref:r,className:_e("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(bk,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Wd.displayName=Bd.displayName;const ST=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});ST.displayName="DialogHeader";const Hd=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-2xl font-semibold leading-none tracking-tight",e),...t}));Hd.displayName=Ud.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));mW.displayName=Vd.displayName;function m1(){return m1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,p=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(m),_=p.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function RT(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&RT(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return RT(t.current,e)||(t.current=e),t.current}var o2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),p=d.useRef(f);u?p.current=f:p.current=t;var m=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!SW(y,m==null?void 0:m.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!$T(R,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){o2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||P0(l,m==null?void 0:m.splitKey).forEach(function(A){var D,B=A0(A,m==null?void 0:m.combinationKey);if(_W(R,B,m==null?void 0:m.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,m==null?void 0:m.preventDefault),!xW(R,B,m==null?void 0:m.enabled)){o2(R);return}p.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(ET(hs(R.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&S(R))},_=function(R){R.key!==void 0&&(CT(hs(R.code)),i.current=!1,m!=null&&m.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.addHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&P0(l,m==null?void 0:m.splitKey).forEach(function(C){return x.removeHotkey(A0(C,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},vh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=eT(!1);return Zn("h",()=>{t()}),v.jsxs(eg,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Wd,{children:v.jsxs(ST,{children:[v.jsx(Hd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[vh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[vh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[vh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[vh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const kT="Popover",[TT,wte]=Mn(kT,[Fs]),Ax=Fs(),[OW,Rc]=TT(kT),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,p]=d.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Fd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>p(!0),[]),onCustomAnchorRemove:d.useCallback(()=>p(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":MT(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Wm,Y({asChild:!0},i),l)}),PT="PopoverPortal",[LW,FW]=TT(PT,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(PT,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Jm(s)},[]),d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(AT,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(AT,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),AT=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:p,...m}=e,g=Rc(dd,n),y=Ax(n);return Zm(),d.createElement(Xm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:p,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Hm,Y({"data-state":MT(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function MT(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,OT=zW,KW=VW,GW=WW,NT=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(OT,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:_e("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));NT.displayName=OT.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;nv.jsx("textarea",{className:_e("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50","overflow-auto",e),tabIndex:-1,ref:n,...t}));Dx.displayName="Textarea";const yH=()=>{const[e,t,n,r,o,i]=bt(x=>[x.getIsProcessing(),x.settings.prompt,x.updateSettings,x.runInpainting,x.showPrevMask,x.hidePrevMask]),[s,l]=Nx(!1),u=d.useRef(null);DT(u,()=>{u!=null&&u.current&&u.current.blur()});const f=x=>{x.preventDefault(),x.stopPropagation();const S=x.target;n({prompt:S.value})},p=()=>{e||r()},m=x=>{x.key==="Enter"&&x.ctrlKey&&t.length!==0&&p()},g=()=>{o()},y=()=>{i()};return v.jsx("div",{className:"flex gap-4 relative w-full justify-center h-full",children:v.jsxs("div",{className:"absolute flex gap-4",children:[v.jsx(Dx,{ref:u,placeholder:"I want to repaint of...",className:_e(s?"focus:overflow-y-auto":"overflow-y-hidden","min-h-[32px] h-[32px] overflow-x-hidden focus:h-[120px] overflow-y-hidden transition-[height] w-[500px] py-1 px-3 bg-background resize-none"),style:{scrollbarGutter:"stable"},value:t,onInput:f,onKeyUp:m,onTransitionEnd:l}),v.jsx(wn,{size:"sm",onClick:p,disabled:e,onMouseEnter:g,onMouseLeave:y,children:"Paint"})]})})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,p="__lodash_placeholder__",m=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",Sg=/\b__p \+= '';/g,_g=/\b(__p \+=) '' \+/g,Qd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),Eg=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,Jd=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Cg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,$g=/^\w*$/,Rg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,ef=/\{\n\/\* \[wrapped with (.+)\] \*/,a6=/,? & /,l6=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,c6=/[()=,{}\[\]\/\s]/,u6=/\\(\\)?/g,d6=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,mb=/\w*$/,f6=/^[-+]0x[0-9a-f]+$/i,h6=/^0b[01]+$/i,p6=/^\[object .+?Constructor\]$/,m6=/^0o[0-7]+$/i,g6=/^(?:0|[1-9]\d*)$/,v6=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,tf=/($^)/,y6=/['\n\r\u2028\u2029\\]/g,nf="\\ud800-\\udfff",w6="\\u0300-\\u036f",x6="\\ufe20-\\ufe2f",b6="\\u20d0-\\u20ff",gb=w6+x6+b6,vb="\\u2700-\\u27bf",yb="a-z\\xdf-\\xf6\\xf8-\\xff",S6="\\xac\\xb1\\xd7\\xf7",_6="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",E6="\\u2000-\\u206f",C6=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",wb="A-Z\\xc0-\\xd6\\xd8-\\xde",xb="\\ufe0e\\ufe0f",bb=S6+_6+E6+C6,kg="['’]",$6="["+nf+"]",Sb="["+bb+"]",rf="["+gb+"]",_b="\\d+",R6="["+vb+"]",Eb="["+yb+"]",Cb="[^"+nf+bb+_b+vb+yb+wb+"]",Tg="\\ud83c[\\udffb-\\udfff]",k6="(?:"+rf+"|"+Tg+")",$b="[^"+nf+"]",Pg="(?:\\ud83c[\\udde6-\\uddff]){2}",Ag="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+wb+"]",Rb="\\u200d",kb="(?:"+Eb+"|"+Cb+")",T6="(?:"+Ua+"|"+Cb+")",Tb="(?:"+kg+"(?:d|ll|m|re|s|t|ve))?",Pb="(?:"+kg+"(?:D|LL|M|RE|S|T|VE))?",Ab=k6+"?",Mb="["+xb+"]?",P6="(?:"+Rb+"(?:"+[$b,Pg,Ag].join("|")+")"+Mb+Ab+")*",A6="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",M6="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ob=Mb+Ab+P6,O6="(?:"+[R6,Pg,Ag].join("|")+")"+Ob,N6="(?:"+[$b+rf+"?",rf,Pg,Ag,$6].join("|")+")",D6=RegExp(kg,"g"),I6=RegExp(rf,"g"),Mg=RegExp(Tg+"(?="+Tg+")|"+N6+Ob,"g"),L6=RegExp([Ua+"?"+Eb+"+"+Tb+"(?="+[Sb,Ua,"$"].join("|")+")",T6+"+"+Pb+"(?="+[Sb,Ua+kb,"$"].join("|")+")",Ua+"?"+kb+"+"+Tb,Ua+"+"+Pb,M6,A6,_b,O6].join("|"),"g"),F6=RegExp("["+Rb+nf+gb+xb+"]"),j6=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,z6=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],B6=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var U6={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},V6={"&":"&","<":"<",">":">",'"':""","'":"'"},W6={"&":"&","<":"<",">":">",""":'"',"'":"'"},H6={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},K6=parseFloat,G6=parseInt,Nb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,Y6=typeof self=="object"&&self&&self.Object===Object&&self,fn=Nb||Y6||Function("return this")(),Og=t&&!t.nodeType&&t,Hs=Og&&!0&&e&&!e.nodeType&&e,Db=Hs&&Hs.exports===Og,Ng=Db&&Nb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Ng&&Ng.binding&&Ng.binding("util")}catch{}}(),Ib=$r&&$r.isArrayBuffer,Lb=$r&&$r.isDate,Fb=$r&&$r.isMap,jb=$r&&$r.isRegExp,zb=$r&&$r.isSet,Bb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function X6(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Dg(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Xb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oM(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iM=jg(U6),sM=jg(V6);function aM(F){return"\\"+H6[F]}function lM(F,te){return F==null?n:F[te]}function Wa(F){return F6.test(F)}function cM(F){return j6.test(F)}function uM(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Vg(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Zb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qM(a,c){var h=this.__data__,w=Sf(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GM,ti.prototype.delete=YM,ti.prototype.get=XM,ti.prototype.has=ZM,ti.prototype.set=qM;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&m,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tO(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return MS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:qS(a),!I)return z?W7(a,h7(N,a)):V7(a,lS(N,a))}else{if(!Et[ae])return $?a:{};N=nO(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),$_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):E_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?mv:pv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p7(a){var c=ln(a);return function(h){return cS(h,a,c)}}function cS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function uS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=of,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Dg,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:k_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Zg=FS(),hS=FS(!0);function $o(a,c){return a&&Zg(a,c,ln)}function qg(a,c){return a&&hS(a,c,ln)}function Ef(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v7(a,c){return a!=null&&yt.call(a,c)}function y7(a,c){return a!=null&&c in St(a)}function w7(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&mf.call(I,z,1),mf.call(a,z,1);return a}function ES(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?mf.call(a,$,1):av(a,$)}}return a}function ov(a,c){return a+yf(oS()*(c-a+1))}function M7(a,c,h,w){for(var $=-1,T=tn(vf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function iv(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=yf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return Sv(e_(a,c,Gn),a+"")}function O7(a){return aS(tl(a))}function N7(a,c){var h=tl(a);return Df(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L7(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function $f(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y7(a);if(re)return af(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var AS=CM||function(a){return fn.clearTimeout(a)};function MS(a,c){if(c)return a.slice();var h=a.length,w=Jb?Jb(h):new a.constructor(h);return a.copy(w),w}function dv(a){var c=new a.constructor(a.byteLength);return new hf(c).set(new hf(a)),c}function j7(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z7(a){var c=new a.constructor(a.source,mb.exec(a));return c.lastIndex=a.lastIndex,c}function B7(a){return Vc?St(Vc.call(a)):{}}function OS(a,c){var h=c?dv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function NS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function DS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function LS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function FS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H7(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function jS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Ig(L_(I_(c).replace(D6,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K7(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function BS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Of(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oO(a){return Ge(a)||Js(a)||!!(nS&&a&&a[nS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&g6.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Df(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,f_(a,h)});function h_(a){var c=k(a);return c.__chain__=!0,c}function m4(a,c){return c(a),a}function If(a,c){return c(a)}var g4=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Xg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:If,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v4(){return h_(this)}function y4(){return new Tr(this.value(),this.__chain__)}function w4(){this.__values__===n&&(this.__values__=R_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x4(){return this}function b4(a){for(var c,h=this;h instanceof bf;){var w=s_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S4(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:If,args:[_v],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(_v)}function _4(){return TS(this.__wrapped__,this.__actions__)}var E4=kf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C4(a,c,h){var w=Ge(a)?Ub:m7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $4(a,c){var h=Ge(a)?Li:fS;return h(a,Ie(c,3))}var R4=zS(a_),k4=zS(l_);function T4(a,c){return hn(Lf(a,c),1)}function P4(a,c){return hn(Lf(a,c),ee)}function A4(a,c,h){return h=h===n?1:qe(h),hn(Lf(a,c),h)}function p_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function m_(a,c){var h=Ge(a)?Z6:dS;return h(a,Ie(c,3))}var M4=kf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O4(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Uf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N4=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D4=kf(function(a,c,h){ri(a,h,c)});function Lf(a,c){var h=Ge(a)?Ot:yS;return h(a,Ie(c,3))}function I4(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),SS(a,c,h))}var L4=kf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F4(a,c,h){var w=Ge(a)?Ig:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j4(a,c,h){var w=Ge(a)?q6:Kb,$=arguments.length<3;return w(a,Ie(c,4),h,$,dS)}function z4(a,c){var h=Ge(a)?Li:fS;return h(a,zf(Ie(c,3)))}function B4(a){var c=Ge(a)?aS:O7;return c(a)}function U4(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u7:N7;return w(a,c)}function V4(a){var c=Ge(a)?d7:I7;return c(a)}function W4(a){if(a==null)return 0;if(Hn(a))return Uf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:tv(a).length}function H4(a,c,h){var w=Ge(a)?Lg:L7;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K4=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),SS(a,hn(c,1),[])}),Ff=$M||function(){return fn.Date.now()};function G4(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function g_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function v_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Cv=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Cv));w|=P}return oi(a,w,c,h,$)}),y_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(y_));w|=P}return oi(c,w,a,h,$)});function w_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=w_.placeholder,w}function x_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=x_.placeholder,w}function b_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,z_=c-no;return ae?En(z_,T-ci):z_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=Ff();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&AS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(Ff())}function cr(){var Yt=Ff(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return AS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y4=et(function(a,c){return uS(a,1,c)}),X4=et(function(a,c,h){return uS(a,Or(c)||0,h)});function Z4(a){return oi(a,B)}function jf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(jf.Cache||ni),h}jf.Cache=ni;function zf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q4(a){return v_(2,a)}var Q4=F7(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=mS(function(){return arguments}())?mS:function(a){return Bt(a)&&yt.call(a,"callee")&&!tS.call(a,"callee")},Ge=Q.isArray,hN=Ib?ir(Ib):b7;function Hn(a){return a!=null&&Bf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function pN(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kM||Lv,mN=Lb?ir(Lb):S7;function gN(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function vN(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!tv(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function yN(a,c){return Gc(a,c)}function wN(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function Rv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function xN(a){return typeof a=="number"&&rS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function __(a){return typeof a=="number"&&a==qe(a)}function Bf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var E_=Fb?ir(Fb):E7;function bN(a,c){return a===c||ev(a,c,vv(c))}function SN(a,c,h){return h=typeof h=="function"?h:n,ev(a,c,vv(c),h)}function _N(a){return C_(a)&&a!=+a}function EN(a){if(aO(a))throw new Ke(i);return gS(a)}function CN(a){return a===null}function $N(a){return a==null}function C_(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=pf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&uf.call(h)==SM}var kv=jb?ir(jb):C7;function RN(a){return __(a)&&a>=-H&&a<=H}var $_=zb?ir(zb):$7;function Uf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=Bb?ir(Bb):R7;function kN(a){return a===n}function TN(a){return Bt(a)&&Cn(a)==ke}function PN(a){return Bt(a)&&On(a)==ft}var AN=Mf(nv),MN=Mf(function(a,c){return a<=c});function R_(a){if(!a)return[];if(Hn(a))return Uf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uM(a[jc]());var c=Cn(a),h=c==ct?Vg:c==q?af:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function k_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Gb(a);var h=h6.test(a);return h||m6.test(a)?G6(a.slice(2),h?2:8):f6.test(a)?W:+a}function T_(a){return Ro(a,Kn(a))}function ON(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var NN=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),P_=qa(function(a,c){Ro(c,Kn(c),a)}),Vf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),DN=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),IN=ii(Xg);function LN(a,c){var h=Za(a);return c==null?h:lS(h,c)}var FN=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,mv(a),h),w&&(h=Pr(h,m|g|y,X7));for(var $=c.length;$--;)av(h,c[$]);return h});function n8(a,c){return M_(a,zf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P7(a,c)});function M_(a,c){if(a==null)return{};var h=Ot(mv(a),function(w){return[w]});return c=Ie(c),_S(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var O_=HS(ln),N_=HS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(pf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:av(a,c)}function c8(a,c,h){return a==null?a:kS(a,c,uv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:kS(a,c,uv(h),w)}function tl(a){return a==null?[]:Ug(a,ln(a))}function d8(a){return a==null?[]:Ug(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w7(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=oS();return En(a+$*(c-a+K6("1e-"+(($+"").length-1))),c)}return ov(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?D_(c):c)});function D_(a){return Av(vt(a).toLowerCase())}function I_(a){return a=vt(a),a&&a.replace(v6,iM).replace(I6,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&Eg.test(a)?a.replace(Nc,sM):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=jS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Af(yf($),h)+a+Af(vf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!kv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Av(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Vf({},c,w,KS);var $=Vf({},c.imports,w.imports,KS),T=ln($),N=Ug($,T),I,z,re=0,oe=c.interpolate||tf,ae="__p += '",ge=Wg((c.escape||tf).source+"|"+oe.source+"|"+(oe===Lc?d6:tf).source+"|"+(c.evaluate||tf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++B6+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(y6,aM),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(c6.test(Le))throw new Ke(l);ae=(z?ae.replace(Sg,""):ae).replace(_g,"$1").replace(Qd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=F_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,Rv(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Gb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Yb(w,$),N=Xb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,qb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Xb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Yb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),kv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Wg($.source,vt(mb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pM):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Av=jS("toUpperCase");function L_(a,c,h){return a=vt(a),c=h?n:c,c===n?cM(a)?vM(a):eM(a):a.match(c)||[]}var F_=et(function(a,c){try{return or(a,n,c)}catch(h){return Rv(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Cv(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=Bg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:If,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=lf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Tf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jM,ot.prototype.reverse=zM,ot.prototype.value=BM,k.prototype.at=g4,k.prototype.chain=v4,k.prototype.commit=y4,k.prototype.next=w4,k.prototype.plant=b4,k.prototype.reverse=S4,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_4,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x4),k},Ka=yM();Hs?((Hs.exports=Ka)._=Ka,Og._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((p,m)=>{const g=u+p,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function IT(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=IT(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:p}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,p);if(S===void 0)break;m.set(x,S)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const p=[];for(let m=1;m({photo:x,index:S})).slice(f[m-1],f[m]),y=IT(g.map(({photo:x})=>x),o,n,r);p.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return p}function tg(...e){return[...e].filter(t=>!!t).join(" ")}function LT(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:LT("100%",e,t)}function c2(e,t,n){var r,o;return LT((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${c2(l,t,n)}`).concat(c2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ix(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:p}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{p({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:tg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(m);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:tg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:p,weight:m})=>{let g=o.get(p);g||(g=[],o.set(p,g));const y=f+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function u2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,p)=>f+p,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),m=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[f]/u;l.push(p.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:p.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,p=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),m=LH(p,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=u2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function FT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:p}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return p.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?FT({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:p,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return FT({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((m,g)=>m+g,0),p=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+p,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function jT(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:tg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:p}=l;return d.createElement(d.Fragment,null,u.map((m,g)=>d.createElement(jT,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:p,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>d.createElement(Ix,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function zT(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?zT({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let p=0;p{const y=u.reduce((x,S,E)=>S[])).map(p=>p.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:p.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zT({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(jT,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:p,layout:m})=>d.createElement(Ix,{key:p.key||p.src,photo:p,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:tg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Lx(e,t){return typeof e=="function"?e(t):e}function BT(e,t){return typeof e<"u"?Lx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Lx(e[n>=0?n:0],t)}function yh(e,t,n,r=0){const o=BT(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:yh(i,n,[5,4,3,2],1),spacing:yh(s,n,[20,15,10,5]),padding:yh(l,n,[0,0,0,0,0]),targetRowHeight:yh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:BT(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Lx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:p}=f||{};if(p){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*p-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):WT(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function UT(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&WT(e)=="[object Boolean]"}function VT(e){return typeof e=="object"}function gK(e){return VT(e)&&e!==null}function pr(e){return e!=null}function M0(e){return!e.trim().length}function WT(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,d2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=HT(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function HT(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=f2(e),n=g1(e);else{if(!d2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,d2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=f2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function f2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||UT(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let p=0,m=f.length;pe.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:p}=u.pop();if(pr(p))if(Bo(p)&&!M0(p)){let m={v:p,i:f,n:this.norm.get(p)};l.push(m)}else ki(p)&&p.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Bo(s)&&!M0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function KT(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Fx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(HT)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Fx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function wh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const p=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const S=l>1||u,E=S?Array(m):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=wh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+p,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=wh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(wh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>la){let g=0;const y=m%la,x=m-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),m+=b,_&&C&&(p=[...p,...C])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=p),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return h2(t,this.multiRegex)}static isSingleMatch(t){return h2(t,this.singleRegex)}search(){}}function h2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class YT extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new GT(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class XT extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,XT,IK,LK,jK,FK,DK,YT],p2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&VT(e)&&!b1(e),m2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function ZT(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(m2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const p={keyId:g1(u),pattern:f};return n&&(p.searcher=w1(f,t)),p}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(p=>{l.children.push(r(p))})}),l};return b1(e)||(e=m2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Fx))throw new Error(vK);this._myIndex=n||KT(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:p}]})}),o}_searchLogical(t){const n=ZT(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const p=[];for(let m=0,g=l.children.length;m{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:p})=>{i[u].matches.push(...p)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,p)=>{u.push(...this._findMatches({key:f,value:s[p],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:p}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:p})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=KT;kc.parseIndex=PK;kc.config=He;kc.parseQuery=ZT;HK(WK);function Kd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",p="data-radix-collection-item",m=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[p]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${p}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const O0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},jx="RovingFocusGroup",[S1,qT,eG]=Kd(jx),[tG,ng]=Mn(jx,[eG]),[nG,rG]=tG(jx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...p}=e,m=d.useRef(null),g=Ue(t,m),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=qT(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(O0,b),()=>A.removeEventListener(O0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},p,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(O0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);QT(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),p=f.currentTabStopId===u,m=qT(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:p?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=m().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>QT(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function QT(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const JT=oG,e3=aG,t3="Tabs",[fG,xte]=Mn(t3,[ng]),n3=ng(),[hG,zx]=fG(t3),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,p=Tc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:p,activationMode:u},d.createElement(Ae.div,Y({dir:p,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=zx(mG,n),s=n3(n);return d.createElement(JT,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=zx(vG,n),l=n3(n),u=r3(s.baseId,r),f=o3(s.baseId,r),p=r===s.value;return d.createElement(e3,Y({asChild:!0},l,{focusable:!o,active:p}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":p,"aria-controls":f,"data-state":p?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!p&&!o&&m&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=zx(wG,n),u=r3(l.baseId,r),f=o3(l.baseId,r),p=r===l.value,m=d.useRef(p);return d.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||p},({present:g})=>d.createElement(Ae.div,Y({"data-state":p?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function r3(e,t){return`${e}-trigger-${t}`}function o3(e,t){return`${e}-content-${t}`}const bG=pG,i3=gG,s3=yG,a3=xG,l3=bG,Bx=d.forwardRef(({className:e,...t},n)=>v.jsx(i3,{ref:n,className:_e("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Bx.displayName=i3.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(s3,{ref:n,className:_e("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=s3.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(a3,{ref:n,className:_e("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=a3.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function Ux(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],rg="Select",[og,ig,EG]=Kd(rg),[Pc,bte]=Mn(rg,[EG,Fs]),Vx=Fs(),[CG,Fa]=Pc(rg),[$G,RG]=Pc(rg),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:p,autoComplete:m,disabled:g,required:y}=e,x=Vx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(Fd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(og.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(h3,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:p,autoComplete:m,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Vx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=ig(n),[p,m,g]=p3(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=m3(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Wm,Y({asChild:!0},i),d.createElement(Ae.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":f3(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=p.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,p=i!==void 0,m=Ue(t,u.onValueNodeChange);return An(()=>{f(p)},[f,p]),d.createElement(Ae.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),f3(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(jd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(c3,{scope:e.__scopeSelect},d.createElement(og.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[c3,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=ig(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Jm(C)},[C]),Zm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=p3(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=m3(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?g2:LG,Ne=We===g2?{side:l,sideOffset:u,align:f,alignOffset:p,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(c3,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(Qm,{as:Zo,allowPinchZoom:!0},d.createElement(Xm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ue(t,A=>p(A)),g=ig(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),g2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Vx(n);return d.createElement(Hm,Y({},s,i,{ref:t,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)"}}))}),[FG,Wx]=Pc(dc,{}),v2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(v2,n),i=Wx(v2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(og.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&p){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(x,S);if(E0?C:0,p.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,u3]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[p,m]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{m(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(og.ItemSlot,{scope:n,value:r,disabled:o,textValue:p},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),xh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(xh,n),l=ja(xh,n),u=u3(xh,n),f=RG(xh,n),[p,m]=d.useState(null),g=Ue(t,_=>m(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=p==null?void 0:p.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u3(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),y2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(y2,e.__scopeSelect),r=Wx(y2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollTop>0;i(p)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),w2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(w2,e.__scopeSelect),r=Wx(w2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const p=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(d3,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),d3=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=ig(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const p=l().find(m=>m.ref.current===document.activeElement);p==null||(f=p.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function f3(e){return e===""||e===void 0}const h3=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=Ux(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,p=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&p){const m=new Event("change",{bubbles:!0});p.call(l,n),l.dispatchEvent(m)}},[s,n]),d.createElement(Km,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});h3.displayName="BubbleSelect";function p3(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function m3(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,g3=PG,nY=MG,rY=OG,oY=NG,v3=DG,iY=jG,sY=VG,y3=HG,w3=GG,aY=YG,lY=ZG,x3=qG,b3=QG,S3=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g3,{ref:r,className:_e("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=g3.displayName;const _3=d.forwardRef(({className:e,...t},n)=>v.jsx(x3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));_3.displayName=x3.displayName;const E3=d.forwardRef(({className:e,...t},n)=>v.jsx(b3,{ref:n,className:_e("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));E3.displayName=b3.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(v3,{ref:o,className:_e("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(_3,{}),v.jsx(iY,{className:_e("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(E3,{})]})}));vo.displayName=v3.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:_e("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=y3.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(w3,{ref:r,className:_e("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(xk,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=w3.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(S3,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=S3.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const C3="ScrollArea",[$3,Ste]=Mn(C3),[fY,qr]=$3(C3),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,p]=d.useState(null),[m,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:p,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",R3=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(k3,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Hx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},p=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",p),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",p)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(k3,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=ag(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,p=i?"scrollLeft":"scrollTop";if(f){let m=f[p];const g=()=>{const y=f[p];m!==y&&(u("SCROLL"),s()),m=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Hx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),k3=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=ag(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=M3(l.viewport,l.content),p={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=x2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},p,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=x2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"horizontal"},o,{ref:f,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":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.x),onDragScroll:p=>e.onDragScroll(p.x),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+p.deltaX;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(P3,Y({"data-orientation":"vertical"},o,{ref:f,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":sg(n)+"px",...e.style},onThumbPointerDown:p=>e.onThumbPointerDown(p.y),onDragScroll:p=>e.onDragScroll(p.y),onWheelScroll:(p,m)=>{if(i.viewport){const g=i.viewport.scrollTop+p.deltaY;e.onWheelScroll(g),N3(g,m)&&p.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,T3]=$3(Oi),P3=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:p,onResize:m,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(p),O=Ft(u),A=ag(m,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=T3(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=T3(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,m=>s.onThumbChange(m)),f=d.useRef(),p=ag(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(p(),!f.current){const y=$Y(m,l);f.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,p,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,S=m.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),A3="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(A3,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(A3,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var p;const m=((p=o.scrollbarX)===null||p===void 0?void 0:p.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),fc(o.scrollbarY,()=>{var p;const m=((p=o.scrollbarY)===null||p===void 0?void 0:p.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function M3(e,t){const n=e/t;return isNaN(n)?0:n}function sg(e){const t=M3(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=sg(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,p=n.content-n.viewport,m=r==="ltr"?[0,p]:[p*-1,0];return O3([u,f],m)(e)}function x2(e,t,n="ltr"){const r=sg(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return O3([0,s],[0,l])(f)}function O3(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function N3(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function ag(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const D3=hY,RY=mY,kY=_Y,lg=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(D3,{ref:r,className:_e("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(I3,{}),v.jsx(kY,{})]}));lg.displayName=D3.displayName;const I3=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(R3,{ref:r,orientation:t,className:_e("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));I3.displayName=R3.displayName;const L3="Name",F3="Created time",j3="Modified time",b2="input",TY="output",S2={[Es.NAME]:L3,[Es.CTIME]:F3,[Es.MTIME]:j3};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=Nx(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[p,m]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(b2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||m(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:p,left:0})},100)},[r,p]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(eg,{open:r,onOpenChange:o,children:[v.jsx(pT,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Wd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Hd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Bm,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(l3,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(Bx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:b2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:S2[i.sortBy],onValueChange:V=>{switch(V){case L3:s({sortBy:Es.NAME});break;case F3:s({sortBy:Es.CTIME});break;case j3:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(S2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(lg,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Gd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const z3=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&z3(e)&&!$l(e),B3=e=>sn(e)&&e.target?Gd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,U3=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Kx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Kx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Yd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Yd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},V3=je.createContext(null),cg=()=>je.useContext(V3),OY=e=>{const{children:t,...n}=e;return je.createElement(V3.Provider,{value:n},t)};var W3=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,H3=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],K3=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Gx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=cg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),p=je.useRef(o);return p.current=o,Gx({disabled:r,next:m=>u.current&&K3(p.current,m.name,i)&&H3(m,f.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),W3(s,n,f.current,!1)}var Wo=e=>typeof e=="string",G3=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=cg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Gx({disabled:i,subject:n._subjects.values,next:p=>{K3(l.current,p.name,s)&&f(so(G3(l.current,n._names,p.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Yx=e=>/^\w*$/.test(e),Y3=e=>Yd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Yx(t)?[t]:Y3(t),i=o.length,s=i-1;for(;++r{const p=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),p){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?p&&!o._state.action:p)?o.unregister(n):m(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(p=>f.current.onChange({target:{value:B3(p),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:p=>{const m=ve(o._fields,n);m&&p&&(m._f.ref={focus:()=>p.focus(),select:()=>p.select(),setCustomValidity:g=>p.setCustomValidity(g),reportValidity:()=>p.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var X3=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},_2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),E2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Yd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Xx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Kx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Zx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const C2={value:!1,isValid:!1},$2={value:!0,isValid:!0};var Z3=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?$2:{value:e[0].value,isValid:!0}:$2:C2}return C2};const R2={isValid:!1,value:null};var q3=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,R2):R2;function k2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},T2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:p,max:m,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Zx(i),A=Gd(i),D=O||A,B=(S||Xx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=X3.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!Z3(s).isValid||O&&!q3(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(p)||!Fn(m))){let G,se;const U=sl(m),ne=sl(p);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=k2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=k2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!z3(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var Q3=e=>e.type==="select-multiple",BY=e=>Zx(e)||Gd(e),D0=e=>Hp(e)&&e.isConnected,J3=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!J3(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function eP(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!J3(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:eP(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var I0=(e,t)=>eP(e,t,Yp(t)),tP=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function L0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Xx(t)?t.files:Zx(t)?q3(e.refs).value:Q3(t)?[...t.selectedOptions].map(({value:n})=>n):Gd(t)?Z3(e.refs).value:tP(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function P2(e,t,n){const r=ve(e,n);if(r||Yx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Yd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,p=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:N0(),array:N0(),state:N0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=_2(n.mode),S=_2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(p),p=setTimeout(L,Z)},b=async L=>{if(m.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>m.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}m.dirtyFields&&(r.dirtyFields=I0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:L0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=m.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(p),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await T2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!D0(q)):!D0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>G3(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Yd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,tP(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,Q3(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Gd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Xx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(m.isDirty||m.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:I0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),E2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?L0(me._f):B3(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=E2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return m.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=P2(r.errors,o,q),Ii=P2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await T2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:m.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||m.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?L0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(D0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(U3(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),m.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Kx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?I0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Gx({subject:i._subjects.state,next:s=>{H3(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=W3(r,i),t.current}var A2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},nP=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?A2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return A2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&nP(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(p){return p.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=X3(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&nP({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var M2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(M2||(M2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case he.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ce(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),O2=e=>e.status==="aborted",N2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const D2=(e,t)=>{if(Zp(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return D2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return D2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ug.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let F0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ce(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ce(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ce(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ce(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ce(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ce(n,{code:he.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,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ce(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const p=i[f],m=o.data[f];u.push({key:{status:"valid",value:f},value:p._parse(new Qo(o,m,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const p of l)u.push({key:{status:"valid",value:p},value:{status:"valid",value:o.data[p]}});else if(f==="strict")l.length>0&&(Ce(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const p of l){const m=o.data[p];u.push({key:{status:"valid",value:p},value:f._parse(new Qo(o,m,o.path,p)),alwaysSet:p in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const p of u){const m=await p.key;f.push({key:m,value:await p.value,alwaysSet:p.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return rP(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ce(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},p=u._parseSync({data:n.data,path:n.path,parent:f});if(p.status==="valid")return p;p.status==="dirty"&&!i&&(i={result:p,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ce(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class qx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ce(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ce(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new qx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(O2(i)||O2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((N2(i)||N2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ce(r,{code:he.invalid_intersection_types}),Ze)};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}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ce(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ce(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ce(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ce(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,p=await u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,p=u.value;if(f.status==="aborted"||p.status==="aborted")return Ze;(f.status==="dirty"||p.status==="dirty")&&n.dirty(),l.set(f.value,p.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ce(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ce(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const p of u){if(p.status==="aborted")return Ze;p.status==="dirty"&&n.dirty(),f.add(p.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ce(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),p=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),m=await Reflect.apply(s,this,p);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw f.addIssue(o(m,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const p=Reflect.apply(s,this,f.data),m=l._def.returns.safeParse(p,i);if(!m.success)throw new Go([o(p,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ce(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function rP(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ce(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=rP;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ce(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ce(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ce(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ce(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ce(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class ug extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new ug({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;qx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;ug.create;const L1="horizontal",mX=["horizontal","vertical"],oP=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=iP(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});oP.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!iP(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function iP(e){return mX.includes(e)}const sP=oP,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(sP,{ref:o,decorative:n,orientation:t,className:_e("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=sP.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),aP=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Qx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(aP,{ref:r,className:_e(yX(),e,t?"opacity-50":"","select-none"),...n}));Qx.displayName=aP.displayName;const wX=OY,lP=d.createContext({}),al=({...e})=>v.jsx(lP.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),dg=()=>{const e=d.useContext(lP),t=d.useContext(cP),{getFieldState:n,formState:r}=cg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},cP=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(cP.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:_e("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=dg();return v.jsx(Qx,{ref:n,className:_e(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=dg();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=dg();return v.jsx("p",{ref:n,id:r,className:_e("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=dg(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:_e("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const uP="Switch",[bX,_te]=Mn(uP),[SX,_X]=bX(uP),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=m?!!m.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":dP(E),"data-disabled":l?"":void 0,disabled:l,value:u},p,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:m,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":dP(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=Ux(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function dP(e){return e?"checked":"unchecked"}const fP=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(fP,{className:_e("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:_e("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=fP.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[hT]),zs=hT(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(zd,Y({},o,r,{ref:t}))}),hP="AlertDialogContent",[NX,DX]=PX(hP),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:hP,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Bd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var p;f.preventDefault(),(p=u.current)===null||p===void 0||p.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Ud,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,pP=OX,mP=IX,gP=zX,vP=UX,yP=FX,wP=jX,HX=VX,KX=WX,xP=d.forwardRef(({className:e,...t},n)=>v.jsx(pP,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));xP.displayName=pP.displayName;const bP=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(xP,{}),v.jsx(mP,{ref:n,className:_e("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));bP.displayName=mP.displayName;const SP=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});SP.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(yP,{ref:n,className:_e("text-lg font-semibold",e),...t}));GX.displayName=yP.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(wP,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));YX.displayName=wP.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(gP,{ref:n,className:_e(_x(),e),...t}));XX.displayName=gP.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(vP,{ref:n,className:_e(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=vP.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),_P="General",F1="Model",EP="Plugins",QX=[F1,_P,EP];function JX(){const[e,t]=eT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:p}=Id(),[m,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:yk}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=m.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${m.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(m.name);p({title:`Switch to ${$e.name} success`}),u(m)}catch($e){p({variant:"destructive",title:`Switch to ${m.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await y0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await y0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await y0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){p({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,m,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:_e([ee.name===m.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(m.name===ee.name){M=ee.model_type,M===sC&&(M=ch),M===aC&&(M=uh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:m.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(l3,{defaultValue:M,children:[v.jsxs(Bx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:ch,children:"Stable Diffusion"}),v.jsx(pa,{value:uh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:f0,children:"Other Diffusion"})]}),v.jsxs(lg,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:ch,children:G([ch,sC])}),v.jsx(Su,{value:uh,children:G([uh,aC])}),v.jsx(Su,{value:f0,children:G([f0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(bP,{children:v.jsx(SP,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(eg,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Wd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Hd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:_e(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===_P?U():v.jsx(v.Fragment,{}),n===EP?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(eg,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Wd,{children:[v.jsx(Hd,{children:"Buy me a coffee"}),v.jsx(wT,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,p,m,g,y]=bt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{p()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:_e(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(Jk,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(NT,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},CP={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},$P=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&($P(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function RP(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return $P(e.animation);var s=new Date().getTime()-o,l=s/n,u=CP[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=t.scale-l,m=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):RP(e,r,n,function(y){var x=l+p*y,S=u+m*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,p=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:p}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,p=l,m=r-o-u,g=u;return{minPositionX:f,maxPositionX:p,minPositionY:m,maxPositionY:g}},Jx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,p=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,f,l,p,m,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=Jx(e,t);return e.bounds=n,n};function fg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,p=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=j1(e,l-m,f+m,r),x=j1(t,u-g,p+g,r);return{x:y,y:x}}function hg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,p=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var m=u-t*p,g=f-n*p,y=fg(m,g,o,i,0,0,null);return y}function Xd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var I2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=pg(i,n);return!u},L2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var p=e.bounds,m=p.maxPositionX,g=p.minPositionX,y=p.maxPositionY,x=p.minPositionY,S=n>m||ny||rm?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=hg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,p=u.positionX,m=u.positionY;if(!(s===null||l===null||t===p&&n===m)){var g=fg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var p=t-r.x,m=n-r.y,g=s?u:p,y=l?f:m;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function F2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var p=s+(e-s)*f;return p>u?u:pi?i:p}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),p=t.x-r.x,m=t.y-r.y,g=p/f,y=m/f,x=u-o,S=p*p+m*m,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,p=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=p-G,M=m+se,ee=g-se,H=e.transformState,X=new Date().getTime();RP(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=CP[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=F2(Me,H.positionX,$e,b,y,p,f,ne,U,xe),Mt=F2(Oe,H.positionY,Ve,_,y,g,m,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function j2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function kP(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,p=i||t.1&&m;g?AZ(e):kP(e)}}function eb(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Xd(Wr(t,2),i,s,0,!1),f=vc(e,u),p=hg(e,n,r,u,f,l),m=p.x,g=p.y;return{scale:u,positionX:m,positionY:g}}function TP(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,p=u.animationTime,m=u.animationType,g=f||r>=s;if((r>=1||l)&&kP(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=eb(e,s,y,x);S&&Bs(e,S,p,m)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=pg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},IP=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,p=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Xd(Wr(g,2),s,i,f,!p&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,p=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=m.size,E=m.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=DP(t,i,u),D=E||S===0||p||y,B=f&&D,V=hg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(TP(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=IP(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,p=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=IP(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||p===0||l,E=s&&S,_=hg(e,m.x,m.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,TP(e,t==null?void 0:t.x,t==null?void 0:t.y)},LP=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),OP(e,s,l,function(){return Nt(_t(e),t,o)}),LP(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,p=n.doubleClick,m=p.disabled,g=p.mode,y=p.step,x=p.animationTime,S=p.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=AP(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=DP(t,i,s),C=eb(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),LP(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),p=n&&u&&f&&!s;if(!p)return!1;var m=pg(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=U2(r)},this.initializeWindowEvents=function(){var r,o=z0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=z0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=z0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),j2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=L2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),z2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=I2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,p=u.length===2;f&&(jo(n),j2(n,r),Nt(_t(n),r,i)),p&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=L2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];z2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=NP(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=U2(this.props),this.transformState=PP(this.props)}return e}(),tb=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(tb.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(tb);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,V2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,p=e.contentProps,m=p===void 0?{}:p,g=d.useContext(tb),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(V2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},m,{ref:E,className:"react-transform-component ".concat(V2.content," ").concat(i),style:l}),t))};const FP=["PageUp","PageDown"],jP=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],zP={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Zd="Slider",[U1,gq,vq]=Kd(Zd),[BP,Cte]=Mn(Zd,[vq]),[yq,mg]=BP(Zd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:p,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:p,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),m(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=FP.includes(U.key)||U.shiftKey&&jP.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[UP,VP]=BP(Zd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...p}=e,[m,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||m.getBoundingClientRect(),P=[0,R.width],A=nb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(WP,Y({dir:S,"data-orientation":"horizontal"},p,{ref:y,style:{...p.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=zP[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,p=d.useRef(null),m=Ue(t,p),g=d.useRef(),y=!o;function x(S){const E=g.current||p.current.getBoundingClientRect(),_=[0,E.height],C=nb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(UP,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(WP,Y({"data-orientation":"vertical"},f,{ref:m,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=zP[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),WP=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,p=mg(Zd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):FP.concat(jP).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),p.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),W2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=mg(W2,n),i=VP(W2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>HP(g,o.min,o.max)),p=u>1?Math.min(...f):0,m=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:p+"%",[i.endEdge]:m+"%"}}))}),H2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=mg(H2,n),s=VP(H2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),p=yx(l),m=i.values[r],g=m===void 0?0:HP(m,i.min,i.max),y=Tq(r,i.values.length),x=p==null?void 0:p[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=Ux(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function HP(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=nb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function nb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const KP=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(KP,{ref:n,className:_e("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=KP.displayName;const ll={capture:!0,passive:!1},jq=2,K2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,p,{x:m,y:g,width:y,height:x},S,E,_,b,C,R]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>K2(W,le,m,y,n,o),J=(W,le)=>K2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:_e(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!p?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,G2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:p,width:m,height:g},y,x,S,E,_,b,C]=bt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>G2(ee,H,f,n),D=(ee,H)=>G2(ee,H,p,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,m,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:_e(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:p,initHeight:g,initWidth:m,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),M=()=>v.jsx("div",{className:_e("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:f,top:p},children:[M(),ne(),se()]})})},Gq=200,Yq=3,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,p,m,g,y,x,S,E,_,b,C,R,P,O,A,D]=bt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=bt(K=>K.editorState.baseBrushSize),V=bt(K=>K.getBrushSize()),J=bt(K=>K.editorState.renders),G=bt(K=>K.editorState.extraMasks),se=bt(K=>K.editorState.temporaryMasks),U=bt(K=>K.editorState.lineGroups),ne=bt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),ZR(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var ef;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&p(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((ef=q.current)==null||ef.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(h0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await wk(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(hC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},Sg=K=>{if(g.isInteractiveSeg){const Ye=h0(K),st=[...g.clicks];fC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},_g=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!fC(K)){if(hC(K)){ze(!0);return}ke(!0),x(h0(K))}},Qd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Qd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),l2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},Eg=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-3),m(K)},[B]),Zn("]",()=>{m(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),l2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},Jd=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Cg=K=>{m(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},$g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Rg=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:_e("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:Eg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:_g,onMouseUp:Sg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[Rg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?$g():Lc(Jd(Ve,We))),Re&&Lc(Jd(L,Z)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Cg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Qd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],GP=["ArrowUp","PageDown","End"],Jq=[...Qq,...GP],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},gg="Menu",[md,nQ,rQ]=Kd(gg),[za,YP]=Mn(gg,[rQ,Fs,ng]),vg=Fs(),XP=ng(),[ZP,Us]=za(gg),[oQ,qd]=za(gg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=vg(t),[u,f]=d.useState(null),p=d.useRef(!1),m=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{p.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>p.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(Fd,l,d.createElement(ZP,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:p,dir:g,modal:s},r)))},qP=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=vg(n);return d.createElement(Wm,Y({},o,r,{ref:t}))}),QP="MenuPortal",[sQ,JP]=za(QP,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(QP,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(jd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,rb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Jm(i)},[]),d.createElement(ob,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(ob,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),ob=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=qd(bo,n),b=vg(n),C=XP(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?Qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Zm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Xm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:p,onFocusOutside:m,onInteractOutside:g,onDismiss:y},d.createElement(JT,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Hm,Y({role:"menu","aria-orientation":"vertical","data-state":iA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);GP.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",Y2="menu.itemSelect",ib=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=qd(W1,e.__scopeMenu),l=rb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),p=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(Y2,{bubbles:!0,cancelable:!0});m.addEventListener(Y2,y=>r==null?void 0:r(y),{once:!0}),dx(m,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(eA,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,p),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),f.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;f.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||V1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),eA=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=rb(W1,n),l=XP(n),u=d.useRef(null),f=Ue(t,u),[p,m]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(e3,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":p?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(nA,{scope:e.__scopeMenu,checked:n},d.createElement(ib,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":sb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(nA,{scope:e.__scopeMenu,checked:i},d.createElement(ib,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":sb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),tA="MenuItemIndicator",[nA,yQ]=za(tA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(tA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":sb(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),rA="MenuSub",[bQ,oA]=za(rA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(rA,t),s=vg(t),[l,u]=d.useState(null),[f,p]=d.useState(null),m=Ft(o);return d.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),d.createElement(Fd,s,d.createElement(ZP,{scope:t,open:r,onOpenChange:m,content:f,onContentChange:p},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},Sh="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(Sh,e.__scopeMenu),r=qd(Sh,e.__scopeMenu),o=oA(Sh,e.__scopeMenu),i=rb(Sh,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},p=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>p,[p]),d.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),d.createElement(qP,Y({asChild:!0},f),d.createElement(eA,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":iA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),p()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(m=>{var g;p();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+_,y:m.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=JP(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=qd(bo,e.__scopeMenu),l=oA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(ob,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:p=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),p.preventDefault()},onCloseAutoFocus:p=>p.preventDefault(),onFocusOutside:ue(e.onFocusOutside,p=>{p.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,p=>{s.onClose(),p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{const m=p.currentTarget.contains(p.target),g=tQ[s.dir].includes(p.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),p.preventDefault()}})})))))});function iA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function sb(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=p>r&&n<(f-l)*(r-u)/(p-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=qP,OQ=aQ,NQ=cQ,DQ=fQ,IQ=ib,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,sA="DropdownMenu",[WQ,Rte]=Mn(sA,[YP]),_r=YP(),[HQ,aA]=WQ(sA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[p=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:p,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(g=>!g),[m]),modal:l},d.createElement(AQ,Y({},u,{open:p,onOpenChange:m,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=aA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({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:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=aA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,p=u.button===2||f;(!o.modal||p)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,lA=qQ,cA=QQ,uA=JQ,dA=eJ,fA=tJ,hA=nJ,pA=rJ,uJ=oJ,mA=iJ,gA=sJ,dJ=aJ,fJ=lJ,X2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(mA,{ref:o,className:_e("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=mA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(gA,{ref:n,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=gA.displayName;const vA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(lA,{ref:r,sideOffset:t,className:_e("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));vA.displayName=lA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(uA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=uA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(dA,{ref:o,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(xk,{className:"h-4 w-4"})})}),t]}));hJ.displayName=dA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(fA,{ref:r,className:_e("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(hA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=fA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:_e("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=cA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(pA,{ref:n,className:_e("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=pA.displayName;const Z2={RemoveBG:{IconClass:GC,showName:"RemoveBG"},AnimeSeg:{IconClass:GC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:Qk,showName:"RealESRGAN"},GFPGAN:{IconClass:YC,showName:"GFPGAN"},RestoreFormer:{IconClass:YC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r,o]=bt(p=>[p.file,p.serverConfig.plugins,p.isPluginRunning,p.updateInteractiveSegState,p.runRenderablePlugin]),i=!e;if(t.length===0)return null;const s=(p,m)=>{m==="InteractiveSeg"?r({isInteractiveSeg:!0}):o(p,m)},l=()=>v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(Qk,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>o(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),u=p=>{const{IconClass:m,showName:g}=Z2[p.name];return v.jsxs(X2,{children:[v.jsx(H1,{disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>s(!1,p.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>s(!0,p.name),children:"Generate Mask"})]})]},p.name)},f=()=>t.map(p=>{const{IconClass:m,showName:g}=Z2[p.name];return p.name==="RealESRGAN"?l():p.name==="RemoveBG"||p.name==="AnimeSeg"?u(p):v.jsx(fl,{onClick:()=>s(!1,p.name),disabled:i,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),g]})},p.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:n?v.jsx("div",{role:"status",children:v.jsxs("svg",{"aria-hidden":"true",className:"w-5 h-5 animate-spin fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]})}):v.jsx(KU,{strokeWidth:1})})}),v.jsx(vA,{side:"bottom",align:"start",children:f()})]})},yJ=Cx,wJ=xT,xJ=$x,yA=d.forwardRef(({className:e,...t},n)=>v.jsx(zd,{className:_e("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));yA.displayName=zd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),wA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(yA,{}),v.jsx(Bd,{ref:o,className:_e(bJ({side:e}),t),...r,children:n})]}));wA.displayName=Bd.displayName;const xA=({className:e,...t})=>v.jsx("div",{className:_e("flex flex-col space-y-2 text-center sm:text-left",e),...t});xA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Ud,{ref:n,className:_e("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Ud.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:_e("text-sm text-muted-foreground",e),...t}));_J.displayName=Vd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(Zk,{children:[v.jsx(qk,{asChild:!0,children:v.jsx(Qx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},_h=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,p]=bt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[m,g]=Px(n),y=d.useRef(null);DT(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(Dx,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==XR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(Jk,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(_h,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(_h,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(_h,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(_h,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:p,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=Nx(!0);if(Zn("c",()=>{r()}),e.model.name!==lC&&e.model.name!==cC&&e.model.model_type===fs)return null;const o=()=>e.model.name===lC?v.jsx(EJ,{}):e.model.name===cC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(wA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(xA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(lg,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ab=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):q2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):q2(new Blob([t]),r):r(Jo[e]+(t||"")),q2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Q2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let B0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Q2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Q2(e.data));ab(e,!1,n=>{B0||(B0=new TextEncoder),t(B0.encode(n))})}const J2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),p=new Uint8Array(f);for(r=0;r>4,p[o++]=(s&15)<<4|l>>2,p[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",lb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ab(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let U0;function Eh(e){return e.reduce((t,n)=>t+n.length,0)}function Ch(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=p*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Eh(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function yg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=n$(+new Date);return e!==t$?(e$=0,t$=e):e+"."+n$(e$++)}for(;$h{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=TA()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Xo extends qt{constructor(t,n){super(),yg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",r$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,r$,!1)}}function r$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const ub=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),Rh=Br.WebSocket||Br.MozWebSocket,o$=!0,ZJ="arraybuffer",i$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends cb{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=i$?{}:RA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=o$&&!i$?n?new Rh(t,n):new Rh(t):new Rh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{o$&&this.ws.send(i)}catch{}o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!Rh}}class QJ extends cb{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&ub(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=X1(n.host).host),yg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=$A,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(p(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,p(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(m){n&&m.name!==n.name&&i()}const p=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){hl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function db(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ac.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,yg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){ub(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new NA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",wg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:wg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:wg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${wg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${wg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:_e("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[hb,Aee,Mee]=Kd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,xg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,p]=d.useState(0),m=d.useRef(!1),g=d.useRef(!1);return d.createElement(hb.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>p(y=>y+1),[]),onToastRemove:d.useCallback(()=>p(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=xg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),p=d.useRef(null),m=d.useRef(null),g=Ue(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=m.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=m.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(V0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=p.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(a$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});V0(E)}}),d.createElement(hb.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(a$,{ref:p,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});V0(E)}}))}),Lee="ToastFocusProxy",a$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=xg(Lee,n);return d.createElement(Km,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),bg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:p,y:m}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${p}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=UA(bg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:p,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=xg(bg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(hb.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,kh(jee,m,Ve,{discrete:!1})):l$($e,S.swipeDirection,pe)?(R.current=$e,kh(Fee,p,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};l$(ne,S.swipeDirection,S.swipeThreshold)?kh(Bee,y,H,{discrete:!0}):kh(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${bg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=xg(bg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(jd,{asChild:!0},d.createElement(Km,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function kh(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const l$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function V0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,e6=KA,ete=Jee,t6=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:_e("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));t6.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),n6=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:_e(tte({variant:t}),e),tabIndex:-1,...n}));n6.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:_e("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const r6=d.forwardRef(({className:e,...t},n)=>v.jsx(e6,{ref:n,className:_e("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(bk,{className:"h-4 w-4"})}));r6.displayName=e6.displayName;const o6=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:_e("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));o6.displayName=qA.displayName;const i6=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:_e("text-sm opacity-90",e),...t,tabIndex:-1}));i6.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(n6,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(o6,{children:n}),r&&v.jsx(i6,{children:r})]}),o,v.jsx(r6,{})]},t)}),v.jsx(t6,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await yk();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),p=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",p),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",p),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],pb="(prefers-color-scheme: dark)",ste=typeof window>"u",s6=d.createContext(void 0),ate=e=>d.useContext(s6)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:p})=>{const[m,g]=d.useState(()=>c$(o,s)),[y,x]=d.useState(()=>c$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=u$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=u$(R);x(P),m==="system"&&n&&!e&&E("system")},[m,e]);d.useEffect(()=>{const R=window.matchMedia(pb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??m)},[e,m]);const C=d.useMemo(()=>({theme:m,setTheme:_,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,_,e,y,n,i]);return je.createElement(s6.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:p}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",p=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${p}${g(e)}}()`:r?`!function(){try{${p}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${pb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${p}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),c$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},u$=e=>(e||(e=window.matchMedia(pb)),e.matches?"dark":"light"),fte=new pL;W0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-Tqq3L7kY.js b/py/iopaint/web_app/assets/index-Tqq3L7kY.js new file mode 100644 index 0000000..dd1d5aa --- /dev/null +++ b/py/iopaint/web_app/assets/index-Tqq3L7kY.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(e,2,!1,e,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(e){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={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"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("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"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("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"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("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"}]]),sV=Kt("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"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};MJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,OJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends Qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-UXaKiZjP.css b/py/iopaint/web_app/assets/index-UXaKiZjP.css new file mode 100644 index 0000000..9d489eb --- /dev/null +++ b/py/iopaint/web_app/assets/index-UXaKiZjP.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-auto{width:auto}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[500px\]{min-width:500px}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-_6nUWG_P.js b/py/iopaint/web_app/assets/index-_6nUWG_P.js new file mode 100644 index 0000000..6a08871 --- /dev/null +++ b/py/iopaint/web_app/assets/index-_6nUWG_P.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var j=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Pe=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return j(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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. + */var kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,pe=H[le];if(0>>1;le<$e;){var Ve=2*(le+1)-1,We=H[Ve],Ne=Ve+1,fe=H[Ne];if(0>o(We,W))Neo(fe,We)?(H[le]=fe,H[Ne]=W,le=Ne):(H[le]=We,H[Ve]=W,le=Ve);else if(Neo(fe,W))H[le]=fe,H[Ne]=W,le=Ne;else break e}}return X}function o(H,X){var W=H.sortIndex-X.sortIndex;return W!==0?W:H.id-X.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,x=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(H){for(var X=n(f);X!==null;){if(X.callback===null)r(f);else if(X.startTime<=H)r(f),X.sortIndex=X.expirationTime,t(u,X);else break;X=n(f)}}function R(H){if(S=!1,C(H),!x)if(n(u)!==null)x=!0,M(P);else{var X=n(f);X!==null&&ee(R,X.startTime-H)}}function P(H,X){x=!1,S&&(S=!1,_(D),D=-1),y=!0;var W=g;try{for(C(X),p=n(u);p!==null&&(!(p.expirationTime>X)||H&&!J());){var le=p.callback;if(typeof le=="function"){p.callback=null,g=p.priorityLevel;var pe=le(p.expirationTime<=X);X=e.unstable_now(),typeof pe=="function"?p.callback=pe:p===n(u)&&r(u),C(X)}else r(u);p=n(u)}if(p!==null)var $e=!0;else{var Ve=n(f);Ve!==null&&ee(R,Ve.startTime-X),$e=!1}return $e}finally{p=null,g=W,y=!1}}var O=!1,A=null,D=-1,B=5,V=-1;function J(){return!(e.unstable_now()-VH||125le?(H.sortIndex=W,t(f,H),n(u)===null&&H===n(f)&&(S?(_(D),D=-1):S=!0,ee(R,W-le))):(H.sortIndex=pe,t(u,H),x||y||(x=!0,M(P))),H},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(H){var X=g;return function(){var W=g;g=X;try{return H.apply(this,arguments)}finally{g=W}}}})(P$);T$.exports=P$;var XD=T$.exports;/** + * @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. + */var A$=d,yr=XD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function JD(e,t,n,r){if(t===null||typeof t>"u"||QD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(e,2,!1,e,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(e){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(e){return e[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(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Y0(t);case 8:return t===cw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function ty(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ce(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(B=A,A=null):B=A.sibling;var V=g(_,A,C[D],R);if(V===null){A===null&&(A=B);break}e&&A&&V.alternate===null&&t(_,A),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V,A=B}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(B=A,A=null):B=A.sibling;var J=g(_,A,V.value,R);if(J===null){A===null&&(A=B);break}e&&A&&J.alternate===null&&t(_,A),b=i(J,b,D),O===null?P=J:O.sibling=J,O=J,A=B}if(V.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!V.done;D++,V=C.next())V=p(_,V.value,R),V!==null&&(b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return Dt&&ta(_,D),P}for(A=r(_,A);!V.done;D++,V=C.next())V=y(A,_,D,V.value,R),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?D:V.key),b=i(V,b,D),O===null?P=V:O.sibling=V,O=V);return e&&A.forEach(function(G){return t(_,G)}),Dt&&ta(_,D),P}function E(_,b,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,O=b;O!==null;){if(O.key===P){if(P=C.type,P===ml){if(O.tag===7){n(_,O.sibling),b=o(O,C.props.children),b.return=_,_=b;break e}}else if(O.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===O.type){n(_,O.sibling),b=o(O,C.props),b.ref=iu(_,O,C),b.return=_,_=b;break e}n(_,O);break}else t(_,O);O=O.sibling}C.type===ml?(b=$a(C.props.children,_.mode,R,C.key),b.return=_,_=b):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,b,C),R.return=_,_=R)}return s(_);case pl:e:{for(O=C.key;b!==null;){if(b.key===O)if(b.tag===4&&b.stateNode.containerInfo===C.containerInfo&&b.stateNode.implementation===C.implementation){n(_,b.sibling),b=o(b,C.children||[]),b.return=_,_=b;break e}else{n(_,b);break}else t(_,b);b=b.sibling}b=c0(C,_.mode,R),b.return=_,_=b}return s(_);case Ji:return O=C._init,E(_,b,O(C._payload),R)}if(yu(C))return x(_,b,C,R);if(eu(C))return S(_,b,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,b!==null&&b.tag===6?(n(_,b.sibling),b=o(b,C),b.return=_,_=b):(n(_,b),b=l0(C,_.mode,R),b.return=_,_=b),s(_)):n(_,b)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ce(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var S=x.memoizedProps,E=x.memoizedState,_=t.stateNode,b=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return x=LE,LE=!1,x}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ty(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Py(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(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||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ce(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ce(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ce(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Pe(this,ga,void 0);Pe(this,rs,void 0);Pe(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){j(this,rs)||this.setEventListener(j(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=j(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){j(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof j(this,ga)=="boolean"?j(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Pe(this,Ll,!0);Pe(this,os,void 0);Pe(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){j(this,os)||this.setEventListener(j(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=j(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=j(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){j(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return j(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},x=()=>new Promise(E=>{var _;o=b=>{const C=r||!p();return C&&E(b),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var O;if(r)return;const b=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=b===!0||typeof b=="number"&&n{if(p())return x()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():x().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Pe(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){j(this,va)&&(clearTimeout(j(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Pe(this,Bl);Pe(this,ao);Pe(this,jl,void 0);Pe(this,zl,void 0);Pe(this,Nr,void 0);Pe(this,is,void 0);Pe(this,Dr,void 0);Pe(this,cn,void 0);Pe(this,vd,void 0);Pe(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=j(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!j(this,cn).length&&this.state.fetchStatus==="idle"&&j(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=j(this,is);return(r=j(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(j(this,jl))}isActive(){return j(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||j(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}onOnline(){var n;const t=j(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=j(this,Dr))==null||n.continue()}addObserver(t){j(this,cn).includes(t)||(j(this,cn).push(t),this.clearGcTimeout(),j(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){j(this,cn).includes(t)&&(ye(this,cn,j(this,cn).filter(n=>n!==t)),j(this,cn).length||(j(this,Dr)&&(j(this,ya)?j(this,Dr).cancel({revert:!0}):j(this,Dr).cancelRetry()),this.scheduleGc()),j(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return j(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(j(this,is))return(f=j(this,Dr))==null||f.continueRetry(),j(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=j(this,cn).find(x=>x.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(x=j(this,Nr).config).onError)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(x=j(this,Nr).config).onSuccess)==null||S.call(x,y,this),(_=(E=j(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,j(this,Dr).promise),j(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...j(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&j(this,zl)?{...j(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{j(this,cn).forEach(r=>{r.onQueryUpdate()}),j(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Pe(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){j(this,Mo).has(t.queryHash)||(j(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=j(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&j(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return j(this,Mo).get(t)}getAll(){return[...j(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Pe(this,No);Pe(this,Oo,void 0);Pe(this,yd,void 0);Pe(this,dr,void 0);Pe(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...j(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){j(this,Oo).includes(t)||(j(this,Oo).push(t),this.clearGcTimeout(),j(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,j(this,Oo).filter(n=>n!==t)),this.scheduleGc(),j(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){j(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():j(this,dr).remove(this))}continue(){var t;return((t=j(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,x,S,E,_,b,C,R,P,O,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,B)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:B})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),j(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=j(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const B=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));B!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:B,variables:t})}const D=await n();return await((f=(u=j(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=j(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(x=this.options).onSettled)==null?void 0:S.call(x,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=j(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(b=this.options).onError)==null?void 0:C.call(b,D,t,this.state.context)),await((P=(R=j(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(O=this.options).onSettled)==null?void 0:A.call(O,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{j(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),j(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Pe(this,Ir,void 0);Pe(this,wd,void 0);Pe(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){j(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,j(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{j(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return j(this,Ir)}find(t){const n={exact:!0,...t};return j(this,Ir).find(r=>XE(n,r))}findAll(t={}){return j(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(j(this,wa)??Promise.resolve()).then(()=>{const t=j(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),j(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,S,E,_,b;const o=t.options,i=(E=(S=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const O={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(O);const A=await p(O),{maxPages:D}=t.options,B=P?tL:eL;return{pages:B(C.pages,A,D),pageParams:B(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},O=R(o,P);y=await g(P,O,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Pe(this,nn,void 0);Pe(this,ss,void 0);Pe(this,as,void 0);Pe(this,Vl,void 0);Pe(this,Wl,void 0);Pe(this,ls,void 0);Pe(this,Hl,void 0);Pe(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,j(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),j(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),j(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,j(this,ls)===0&&((e=j(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=j(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return j(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return j(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=j(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return j(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=j(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=j(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=j(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>j(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(j(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>j(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=j(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return j(this,ss).resumePausedMutations()}getQueryCache(){return j(this,nn)}getMutationCache(){return j(this,ss)}getDefaultOptions(){return j(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){j(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...j(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){j(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...j(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...j(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...j(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){j(this,nn).clear(),j(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Pe(this,Ea);Pe(this,bd);Pe(this,Sd);Pe(this,_d);Pe(this,Ed);Pe(this,Cd);Pe(this,$d);Pe(this,Rd);Pe(this,um);Pe(this,Xn,void 0);Pe(this,Ct,void 0);Pe(this,Gl,void 0);Pe(this,kn,void 0);Pe(this,xa,void 0);Pe(this,Yl,void 0);Pe(this,Do,void 0);Pe(this,xd,void 0);Pe(this,Xl,void 0);Pe(this,Zl,void 0);Pe(this,ba,void 0);Pe(this,Sa,void 0);Pe(this,cs,void 0);Pe(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(j(this,Ct).addObserver(this),eC(j(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(j(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(j(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),j(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=j(this,Ct);if(this.options=j(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||j(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:j(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(j(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(j(this,Ct)!==o||this.options.enabled!==r.enabled||s!==j(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=j(this,Xn).getQueryCache().build(j(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,j(this,Ct).state)),r}getCurrentResult(){return j(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(j(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return j(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=j(this,Xn).defaultQueryOptions(t),r=j(this,Xn).getQueryCache().build(j(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),j(this,kn)))}createResult(t,n){var O;const r=j(this,Ct),o=this.options,i=j(this,kn),s=j(this,xa),l=j(this,Yl),f=t!==r?t.state:j(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:x}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),B=A&&tC(t,r,n,o);(D||B)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===j(this,xd))E=j(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((O=j(this,Zl))==null?void 0:O.state.data,j(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(x="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}j(this,Do)&&(p=j(this,Do),E=j(this,Xl),g=Date.now(),x="error");const _=y==="fetching",b=x==="pending",C=x==="error",R=b&&_;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!b,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=j(this,kn),r=this.createResult(j(this,Ct),this.options);if(ye(this,xa,j(this,Ct).state),ye(this,Yl,this.options),j(this,xa).data!==void 0&&ye(this,Zl,j(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!j(this,_a).size)return!0;const u=new Set(l??j(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(j(this,kn)).some(f=>{const m=f;return j(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=j(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||j(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(j(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{j(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(j(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(j(this,cs))||j(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},j(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){j(this,ba)&&(clearTimeout(j(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){j(this,Sa)&&(clearInterval(j(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=j(this,Xn).getQueryCache().build(j(this,Xn),this.options);if(t===j(this,Ct))return;const n=j(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(j(this,kn))}),j(this,Xn).getQueryCache().notify({query:j(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\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$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),x=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),b=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),O=kt("skew"),A=kt("space"),D=kt("translate"),B=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],se=()=>["",oo,Gi],U=()=>["auto",ha,Je],ne=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],M=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],H=()=>["start","end","center","between","around","evenly","stretch"],X=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ha,ch],pe=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:G(),borderWidth:se(),contrast:le(),grayscale:X(),hueRotate:pe(),invert:X(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:X(),skew:pe(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...ne(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:B()}],"overscroll-x":[{"overscroll-x":B()}],"overscroll-y":[{"overscroll-y":B()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:X()}],shrink:[{shrink:X()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...H()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...H(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...H(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...M(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ne(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...M(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:M()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...M()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ee()}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:pe()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:pe()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),ie={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}ie.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:ie.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return ie.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return ie.isPlainObject(e)||ie.isArray(e)}function iT(e){return ie.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return ie.isArray(e)&&!e.some(qy)}const oj=ie.toFlatObject(ie,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!ie.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=ie.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!ie.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&ie.isSpecCompliantForm(t);if(!ie.isFunction(o))throw new TypeError("visitor must be a function");function f(x){if(x===null)return"";if(ie.isDate(x))return x.toISOString();if(!u&&ie.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return ie.isArrayBuffer(x)||ie.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function m(x,S,E){let _=x;if(x&&!E&&typeof x=="object"){if(ie.endsWith(S,"{}"))S=r?S:S.slice(0,-2),x=JSON.stringify(x);else if(ie.isArray(x)&&rj(x)||(ie.isFileList(x)||ie.endsWith(S,"[]"))&&(_=ie.toArray(x)))return S=iT(S),_.forEach(function(C,R){!(ie.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(x)?!0:(t.append(pC(E,S,i),f(x)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(x,S){if(!ie.isUndefined(x)){if(p.indexOf(x)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(x),ie.forEach(x,function(_,b){(!(ie.isUndefined(_)||_===null)&&o.call(t,_,ie.isString(b)?b.trim():b,S,g))===!0&&y(_,S?S.concat(b):[b])}),p.pop()}}if(!ie.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=ie.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){ie.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&ie.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return ie.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&ie.isArray(o)?o.length:s,u?(ie.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!ie.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&ie.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(ie.isFormData(e)&&ie.isFunction(e.entries)){const n={};return ie.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(ie.isString(e))try{return(t||JSON.parse)(e),ie.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=ie.isObject(t);if(i&&ie.isHTMLForm(t)&&(t=new FormData(t)),ie.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(ie.isArrayBuffer(t)||ie.isBuffer(t)||ie.isStream(t)||ie.isFile(t)||ie.isBlob(t))return t;if(ie.isArrayBufferView(t))return t.buffer;if(ie.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=ie.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&ie.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ie.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=ie.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:ie.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(ie.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!ie.isString(t)){if(ie.isString(r))return t.indexOf(r)!==-1;if(ie.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=ie.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=ie.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>ie.forEach(l,(f,m)=>i(f,m,u));return ie.isPlainObject(t)||t instanceof this.constructor?s(t,n):ie.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(ie.isFunction(n))return n.call(this,o,r);if(ie.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=ie.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=ie.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return ie.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return ie.forEach(this,(o,i)=>{const s=ie.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return ie.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&ie.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return ie.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);ie.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});ie.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return ie.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}ie.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];ie.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),ie.isString(r)&&s.push("path="+r),ie.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=ie.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(ie.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&ie.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&ie.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),ie.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Tj(g);if(x&&zo.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};ie.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>ie.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=ie.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return ie.isPlainObject(f)&&ie.isPlainObject(m)?ie.merge.call({caseless:p},f,m):ie.isPlainObject(m)?ie.merge({},m):ie.isArray(m)?m.slice():m}function o(f,m,p){if(ie.isUndefined(m)){if(!ie.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!ie.isUndefined(m))return r(void 0,m)}function s(f,m){if(ie.isUndefined(m)){if(!ie.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return ie.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);ie.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(ie.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&ie.merge(i.common,i[n.method]);i&&ie.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const x=[xC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,f),g=x.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return ie.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return ie.extend(n,Gh.prototype,t,{allOwnKeys:!0}),ie.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(ie.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Ue(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(x=>{let[S,E]=x;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const b=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return b},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let x;const S=()=>{var E;if(!f)return;s=!1,l.forEach(b=>b(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return x=i.merge(b,(C=r())!=null?C:y),n(x,!0),p()}).then(()=>{_==null||_(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),x||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const x=()=>{var S,E;if(!f)return;s=!1,l.forEach(b=>{var C;return b((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var C;return y=i.merge(b,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{_==null||_(void 0,b)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||x(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @license React + * use-sync-external-store-shim.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. + */var lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return p=x}return p=y}if(x=p,Zz(m,y))return x;var S=r(y);return o!==void 0&&o(x,S)?x:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=je,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],b=[];if(E===!0?(b=m,_=x):(b=p,_=S),b.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,b];e(O=>{O.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const O=y[y.length-2];R=await Nu(O.currentSrc,r.name,r.type)}}else if(y.length>0){const O=y[y.length-1];R=await Nu(O.currentSrc,r.name,r.type)}const P=Wh(i,s,[b],_);if(E){const O=await cC(P);e(A=>{A.editorState.temporaryMasks=[O]})}try{const O=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=O;D&&t().setSeed(parseInt(D,10));const B=new Image;await Vh(B,A);const V=[...y,B];t().setImageSize(B.width,B.height),t().updateEditorState({renders:V,lineGroups:C,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(O){ul({variant:"destructive",description:O.message?O.message:O.toString()})}t().resetRedoState(),e(O=>{O.isInpainting=!1,O.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const x=[...i,y],S=[...s,[]];t().updateEditorState({renders:x,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...x}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>x,Object.values(x));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,x=d.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Ae=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=d.useState({}),S=Ue(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),b=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=b,O=bB(D=>{const B=D.target,V=[...m.branches].some(J=>J.contains(B));!P||V||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const B=D.target;[...m.branches].some(J=>J.contains(B))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>x({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Ae.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,O.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Ae.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},x=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),x=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",b=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],O=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=O?O[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(O)))&&(A=l.floating[C]||i.floating[x]);const D=R/2-P/2,B=A/2-S[x]/2-1,V=Ts(p[_],B),J=Ts(p[b],B),G=V,se=A-S[x]-J,U=A/2-S[x]/2+D,ne=c1(G,U,se),M=!u.arrow&&Cc(o)!=null&&U!=ne&&i.reference[x]/2-(UG<=0)){var B,V;const G=(((B=i.flip)==null?void 0:B.index)||0)+1,se=P[G];if(se)return{data:{index:G,overflows:D},reset:{placement:se}};let U=(V=D.filter(ne=>ne.overflows[0]<=0).sort((ne,M)=>ne.overflows[1]-M.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const ne=(J=D.map(M=>[M.placement,M.overflows.filter(ee=>ee>0).reduce((ee,H)=>ee+H,0)]).sort((M,ee)=>M[1]-ee[1])[0])==null?void 0:J[0];ne&&(U=ne);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:b}=E;return{x:_,y:b}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],x=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",b=y+m[E],C=y-m[_];y=c1(b,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",b=x+m[E],C=x-m[_];x=c1(b,x,C)}const S=l.fn({...t,[g]:y,[p]:x});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],x=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,b;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),O=i.reference[p]+i.reference[C]+(R?0:((b=s.offset)==null?void 0:b[p])||0)-(R?E.crossAxis:0);xO&&(x=O)}return{[g]:y,[p]:x}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let x,S;f==="top"||f==="bottom"?(x=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,x=m==="end"?"top":"bottom");const E=y-u[x],_=g-u[S],b=!t.middlewareData.shift;let C=E,R=_;if(p){const O=g-u.left-u.right;R=m||b?Ts(_,O):O}else{const O=y-u.top-u.bottom;C=m||b?Ts(E,O):O}if(b&&!m){const O=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),B=hr(u.bottom,0);p?R=g-2*(O!==0||A!==0?O+A:hr(u.left,u.right)):C=y-2*(D!==0||B!==0?D+B:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const S=Nl(x),E=x.getBoundingClientRect(),_=Xr(x),b=E.left+(x.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(x.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=b,f+=C,x=vr(x).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),x=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),b={rootMargin:-y+"px "+-x+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const O=P[0].intersectionRatio;if(O!==u){if(!C)return s();O?s(!1,O):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,b)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[b]=_;b&&b.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let x,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,x=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!jp(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[x,S]=d.useState(null),[E,_]=d.useState(null),b=d.useCallback(M=>{M!=O.current&&(O.current=M,S(M))},[S]),C=d.useCallback(M=>{M!==A.current&&(A.current=M,_(M))},[_]),R=i||x,P=s||E,O=d.useRef(null),A=d.useRef(null),D=d.useRef(m),B=VC(u),V=VC(o),J=d.useCallback(()=>{if(!O.current||!A.current)return;const M={placement:t,strategy:n,middleware:g};V.current&&(M.platform=V.current),aU(O.current,A.current,M).then(ee=>{const H={...ee,isPositioned:!0};G.current&&!jp(D.current,H)&&(D.current=H,Is.flushSync(()=>{p(H)}))})},[g,t,n,V]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(M=>({...M,isPositioned:!1})))},[f]);const G=d.useRef(!1);Zh(()=>(G.current=!0,()=>{G.current=!1}),[]),Zh(()=>{if(R&&(O.current=R),P&&(A.current=P),R&&P){if(B.current)return B.current(R,P,J);J()}},[R,P,J,B]);const se=d.useMemo(()=>({reference:O,floating:A,setReference:b,setFloating:C}),[b,C]),U=d.useMemo(()=>({reference:R,floating:P}),[R,P]),ne=d.useMemo(()=>{const M={position:n,left:0,top:0};if(!U.floating)return M;const ee=UC(U.floating,m.x),H=UC(U.floating,m.y);return l?{...M,transform:"translate("+ee+"px, "+H+"px)",...zT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ee,top:H}},[n,l,U.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:J,refs:se,elements:U,floatingStyles:ne}),[m,J,se,U,ne])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Ue(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Ae.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:b=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:O,...A}=e,D=VT(WT,m),[B,V]=d.useState(null),J=Ue(t,Kt=>V(Kt)),[G,se]=d.useState(null),U=yx(G),ne=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,M=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ee=p+(y!=="center"?"-"+y:""),H=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},X=Array.isArray(_)?_:[_],W=X.length>0,le={padding:H,boundary:X.filter(gU),altBoundary:W},{refs:pe,floatingStyles:$e,placement:Ve,isPositioned:We,middlewareData:Ne}=cU({strategy:"fixed",placement:ee,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+M,alignmentAxis:x}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...le}),E&&IB({...le}),UB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Z}=Er.reference,q=Kt.floating.style;q.setProperty("--radix-popper-available-width",`${gt}px`),q.setProperty("--radix-popper-available-height",`${Vs}px`),q.setProperty("--radix-popper-anchor-width",`${L}px`),q.setProperty("--radix-popper-anchor-height",`${Z}px`)}}),G&&lU({element:G,padding:S}),vU({arrowWidth:ne,arrowHeight:M}),R&&LB({strategy:"referenceHidden",...le})]}),[fe,xe]=HT(Ve),Re=Ft(O);An(()=>{We&&(Re==null||Re())},[We,Re]);const Me=(o=Ne.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Ne.arrow)===null||i===void 0?void 0:i.y,ze=((s=Ne.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{B&&ct(window.getComputedStyle(B).zIndex)},[B]),d.createElement("div",{ref:pe.setFloating,"data-radix-popper-content-wrapper":"",style:{...$e,transform:We?$e.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Ne.transformOrigin)===null||l===void 0?void 0:l.x,(u=Ne.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:fe,onArrowChange:se,arrowX:Me,arrowY:Oe,shouldHideArrow:ze},d.createElement(Ae.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(f=Ne.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[x,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return x==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):x==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):x==="right"?(C=`${-y}px`,R=p?E:`${b}px`):x==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${b}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Ae.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Ue(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Ae.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),x=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,b(!0)},[b]),P=d.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),O=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,b(!0)},S)},[S,b]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?O():R()},[u.isOpenDelayed,O,R]),onTriggerLeave:d.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:R,onClose:P,disableHoverableContent:x},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Ue(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Ae.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:ue(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Ue(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((x,S)=>{const E=x.currentTarget,_={x:x.clientX,y:x.clientY},b=NU(_,E.getBoundingClientRect()),C=DU(_,b),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const x=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",x),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",x),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const x=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},b=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);b?g():C&&(g(),f())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.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)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={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"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("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"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("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"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("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"}]]),sV=Jt("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"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Ue(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let b=function(O){if(y.paused||!l)return;const A=O.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(O){if(y.paused||!l)return;const A=O.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(O){if(document.activeElement===document.body)for(const D of O)D.removedNodes.length>0&&Qi(l)};var S=b,E=C,_=R;document.addEventListener("focusin",b),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const x=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const b=S.currentTarget,[C,R]=uV(b);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===b&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Ae.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),x=y[0],S=y[1],E=y[2],_=S-E-i*x;(x||_)&&iP(e,l)&&(p+=_,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),b=n.current,C="deltaX"in S?S.deltaX:b[0]-_[0],R="deltaY"in S?S.deltaY:b[1]-_[1],P,O=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&O.type==="range")return!1;var D=JC(A,O);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,O)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var B=r.current||P;return VV(B,E,S,B==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),b=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(b&&b.should){E.cancelable&&E.preventDefault();return}if(!b){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,b){var C={name:S,delta:E,target:_,should:b};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,x=e.inert;return d.createElement(d.Fragment,null,x?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&x&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Ue(t,o.triggerRef);return d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Ae.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Ue(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Ue(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Ae.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Ae.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!x&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var O;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(O=R.target)!=null&&O.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,B=P0(A,p==null?void 0:p.combinationKey);if(_W(R,B,p==null?void 0:p.ignoreModifiers)||(D=B.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,B,p==null?void 0:p.preventDefault),!xW(R,B,p==null?void 0:p.enabled)){n2(R);return}m.current(R,B),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",_),b.addEventListener("keydown",E),x&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return x.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){b.removeEventListener("keyup",_),b.removeEventListener("keydown",E),x&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return x.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Ue(t,o.triggerRef),l=d.createElement(Ae.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Ue(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.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)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,x=1,S=2,E=1,_=2,b=4,C=8,R=16,P=32,O=64,A=128,D=256,B=512,V=30,J="...",G=800,se=16,U=1,ne=2,M=3,ee=1/0,H=9007199254740991,X=17976931348623157e292,W=NaN,le=4294967295,pe=le-1,$e=le>>>1,Ve=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",B],["partial",P],["partialRight",O],["rearg",D]],We="[object Arguments]",Ne="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",Re="[object Date]",Me="[object DOMException]",Oe="[object Error]",ze="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Z="[object RegExp]",q="[object Set]",we="[object String]",me="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,K=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(K.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Ne]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[Re]=Rt[Oe]=Rt[ze]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Z]=Rt[q]=Rt[we]=Rt[ke]=!1;var Et={};Et[We]=Et[Ne]=Et[ht]=Et[_n]=Et[xe]=Et[Re]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Z]=Et[q]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Oe]=Et[ze]=Et[ke]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var F=Hs&&Hs.require&&Hs.require("util").types;return F||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(F,te,Q){switch(Q.length){case 0:return F.call(te);case 1:return F.call(te,Q[0]);case 2:return F.call(te,Q[0],Q[1]);case 3:return F.call(te,Q[0],Q[1],Q[2])}return F.apply(te,Q)}function XM(F,te,Q,Se){for(var Ke=-1,pt=F==null?0:F.length;++Ke-1}function Ng(F,te,Q){for(var Se=-1,Ke=F==null?0:F.length;++Se-1;);return Q}function Gb(F,te){for(var Q=F.length;Q--&&Va(te,F[Q],0)>-1;);return Q}function oO(F,te){for(var Q=F.length,Se=0;Q--;)F[Q]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(F){return"\\"+HM[F]}function lO(F,te){return F==null?n:F[te]}function Wa(F){return FM.test(F)}function cO(F){return jM.test(F)}function uO(F){for(var te,Q=[];!(te=F.next()).done;)Q.push(te.value);return Q}function Ug(F){var te=-1,Q=Array(F.size);return F.forEach(function(Se,Ke){Q[++te]=[Ke,Se]}),Q}function Yb(F,te){return function(Q){return F(te(Q))}}function ji(F,te){for(var Q=-1,Se=F.length,Ke=0,pt=[];++Q-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var N,I=c&p,z=c&g,re=c&y;if(h&&(N=$?h(a,w,$,T):h(a)),N!==n)return N;if(!It(a))return a;var oe=Ge(a);if(oe){if(N=tN(a),!I)return Wn(a,N)}else{var ae=Cn(a),ge=ae==ze||ae==Mt;if(Hi(a))return PS(a,I);if(ae==gt||ae==We||ge&&!$){if(N=z||ge?{}:XS(a),!I)return z?W6(a,h6(N,a)):V6(a,sS(N,a))}else{if(!Et[ae])return $?a:{};N=nN(a,ae,I)}}T||(T=new eo);var Te=T.get(a);if(Te)return Te;T.set(a,N),E_(a)?a.forEach(function(Fe){N.add(Pr(Fe,c,h,Fe,a,T))}):S_(a)&&a.forEach(function(Fe,nt){N.set(nt,Pr(Fe,c,h,nt,a,T))});var Le=re?z?pv:hv:z?Kn:ln,Qe=oe?n:Le(a);return Rr(Qe||a,function(Fe,nt){Qe&&(nt=Fe,Fe=a[nt]),Wc(N,nt,Pr(Fe,c,h,nt,a,T))}),N}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,N=!0,I=a.length,z=[],re=c.length;if(!I)return z;h&&(c=Ot(c,ir(h))),w?(T=Ng,N=!1):c.length>=o&&(T=Fc,N=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&oe.length>=120)?new Ys(N&&oe):n}oe=a[0];var ae=-1,ge=I[0];e:for(;++ae<$&&re.length-1;)I!==a&&gf.call(I,z,1),gf.call(a,z,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),N=Q(T);T--;)N[w?T:++$]=a,a+=h;return N}function ov(a,c){var h="";if(!a||c<1||c>H)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,N=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=Q($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=$e){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(h?N<=c:N=o){var re=c?null:Y6(a);if(re)return lf(re);N=!1,$=Fc,z=new Ys}else z=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,I=c===null,z=c===c,re=ar(c);if(!I&&!re&&!T&&a>c||T&&N&&z&&!I&&!re||w&&N&&z||!h&&z||!$)return 1;if(!w&&!T&&!re&&a=I)return z;var re=h[w];return z*(re=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,N=h.length,I=-1,z=c.length,re=tn(T-N,0),oe=Q(z+re),ae=!w;++I1?h[$-1]:n,N=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Nn(h[0],h[1],N)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,N=St(h);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),N=w(c),I=N.length;I--;){var z=N[a?I:++$];if(h(T[z],z,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,N=Q(T),I=T,z=Ja($);I--;)N[I]=arguments[I];var re=T<3&&N[0]!==z&&N[T-1]!==z?[]:ji(N,z);if(T-=re.length,T-1?$[T?c[N]:N]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!N&&Nf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:h;++w1&&at.reverse(),oe&&zI))return!1;var re=T.get(a),oe=T.get(c);if(re&&oe)return re==c&&oe==a;var ae=-1,ge=!0,Te=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++ae1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??H,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,Ie(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ee)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,Ie(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,Ie(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?Q(a.length):[];return Bi(a,function(N){T[++w]=$?or(c,N,h):Kc(N,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,Ie(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,Ie(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,Ie(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(Ie(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==q?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,Ie(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,N,I,z,re=0,oe=!1,ae=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(oe=!!h.leading,ae="maxWait"in h,T=ae?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function Te(Yt){var no=w,ci=$;return w=$=n,re=Yt,N=a.apply(ci,no),N}function Le(Yt){return re=Yt,I=qc(nt,c),oe?Te(Yt):N}function Qe(Yt){var no=Yt-z,ci=Yt-re,F_=c-no;return ae?En(F_,T-ci):F_}function Fe(Yt){var no=Yt-z,ci=Yt-re;return z===n||no>=c||no<0||ae&&ci>=T}function nt(){var Yt=jf();if(Fe(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?Te(Yt):(w=$=n,N)}function lr(){I!==n&&TS(I),re=0,w=z=$=I=n}function Dn(){return I===n?N:at(jf())}function cr(){var Yt=jf(),no=Fe(Yt);if(w=arguments,$=this,z=Yt,no){if(I===n)return Le(z);if(ae)return TS(I),I=qc(nt,c),Te(z)}return I===n&&(I=qc(nt,c)),N}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,B)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return h.cache=T.set($,N)||T,N};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(Ie())):Ot(hn(c,1),ir(Ie()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=Q.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==q)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Me||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==ze||c==Mt||c==fe||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=H}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-H&&a<=H}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==ke}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==q?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ee||a===-ee){var c=a<0?-1:1;return c*X}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,le):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?W:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-H,H):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(Ie(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=Ie(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=Ie(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(N,I,z){return c(h,N,I,z)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(K,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),N=Bg($,T),I,z,re=0,oe=c.interpolate||nf,ae="__p += '",ge=Vg((c.escape||nf).source+"|"+oe.source+"|"+(oe===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),Te="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Fe,nt,at,lr,Dn,cr){return at||(at=lr),ae+=a.slice(re,cr).replace(yM,aO),nt&&(I=!0,ae+=`' + +__e(`+nt+`) + +'`),Dn&&(z=!0,ae+=`'; +`+Dn+`; +__p += '`),at&&(ae+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),re=cr+Fe.length,Fe}),ae+=`'; +`;var Le=yt.call(c,"variable")&&c.variable;if(!Le)ae=`with (obj) { +`+ae+` +} +`;else if(cM.test(Le))throw new Ke(l);ae=(z?ae.replace(bg,""):ae).replace(Sg,"$1").replace(Jd,"$1;"),ae="function("+(Le||"obj")+`) { +`+(Le?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(z?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+ae+`return __p +}`;var Qe=I_(function(){return pt(T,Te+"return "+ae).apply(n,N)});if(Qe.source=ae,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),N=Gb(w,$)+1;return Wi(w,T,N).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var N=Jr(a);T=N.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var z=N?Wi(N,0,I).join(""):a.slice(0,I);if($===n)return z+w;if(N&&(I+=z.length-I),Rv($)){if(a.slice(I).search($)){var re,oe=z;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;re=$.exec(oe);)var ae=re.index;z=z.slice(0,ae===n?I:ae)}}else if(a.indexOf(sr($),I)!=I){var ge=z.lastIndexOf($);ge>-1&&(z=z.slice(0,ge))}return z+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=Ie();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$H)return[];var h=le,w=En(a,le);c=Ie(c),a-=le;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var N=this.__wrapped__,I=w?[1]:arguments,z=N instanceof ot,re=I[0],oe=z||Ge(N),ae=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};oe&&h&&typeof re=="function"&&re.length!=1&&(z=oe=!1);var ge=this.__chain__,Te=!!this.__actions__.length,Le=T&&!ge,Qe=z&&!Te;if(!T&&oe){N=Qe?N:new ot(this);var Fe=a.apply(N,I);return Fe.__actions__.push({func:Lf,args:[ae],thisArg:n}),new Tr(Fe,ge)}return Le&&Qe?a.apply(this,I):(Fe=this.thru(ae),Le?w?Fe.value()[0]:Fe.value():Fe)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(N){return c.apply(Ge(N)?N:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),x=i.get(p);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const S=RH(e,i,x,u,n,f,m);if(S===void 0)break;p.set(x,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:x,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:x})=>x),o,n,r);m.push(g.map(({photo:x,index:S},E)=>({photo:x,layout:{height:y,width:y*Vr(x),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=E=>{const{src:_,alt:b,srcSet:C,sizes:R,style:P,...O}=y;return d.createElement("img",{alt:b,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...O})},S=(({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O})=>({display:E,boxSizing:_,width:b,aspectRatio:C,padding:R,marginBottom:P,cursor:O}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:S}))!=null?n:x())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:x})).slice(e[f],e[f+1]),p=o.reduce((y,x,S)=>y+(r[f]-r[S])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:x},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const f=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:x})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((x,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,x=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,x))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),x=_+m,S){let D=0;for(;D=V;U-=1){let ne=U-1,M=n[e.charAt(ne)];if(S&&(E[ne]=+!!M),G[U]=(G[U+1]<<1|1)&M,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(C=xh(t,{errors:A,currentLocation:ne,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,x=ne,x<=g)break;V=Math.max(1,2*g-x)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;b=G}const O={isMatch:x>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(O.indices=A):O.isMatch=!1}return O}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,x=p-y;for(;g{const{isMatch:_,score:b,indices:C}=MK(t,x,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=b,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:S}=y,E=je.useRef(null),_=je.useRef(new Map).current;return je.createElement(o,{scope:x,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=je.forwardRef((y,x)=>{const{scope:S,children:E}=y,_=i(l,S),b=Ue(x,_.collectionRef);return je.createElement(Zo,{ref:b},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=je.forwardRef((y,x)=>{const{scope:S,children:E,..._}=y,b=je.useRef(null),C=Ue(x,b),R=i(f,S);return je.useEffect(()=>(R.itemMap.set(b,{ref:b,..._}),()=>void R.itemMap.delete(b))),je.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const x=i(e+"CollectionConsumer",y);return je.useCallback(()=>{const E=x.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(x.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Ue(t,p),y=Tc(i),[x=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),b=Ft(f),C=ZP(n),R=d.useRef(!1),[P,O]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,b),()=>A.removeEventListener(M0,b)},[b]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>O(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>O(A=>A-1),[])},d.createElement(Ae.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{R.current=!0}),onFocus:ue(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const B=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(B),!B.defaultPrevented){const V=C().filter(ne=>ne.focusable),J=V.find(ne=>ne.active),G=V.find(ne=>ne.id===x),U=[J,G,...V].filter(Boolean).map(ne=>ne.ref.current);qP(U)}}R.current=!1}),onBlur:ue(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Ae.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?f.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=uG(x,f.orientation,f.dir);if(S!==void 0){x.preventDefault();let _=p().filter(b=>b.focusable).map(b=>b.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const b=_.indexOf(x.currentTarget);_=f.loop?dG(_,b+1):_.slice(b+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Ae.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Ae.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Ae.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:ue(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Ae.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,x=Bx(t),[S,E]=d.useState(null),[_,b]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[O=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,B]=Zr({prop:s,defaultProp:l,onChange:u}),V=d.useRef(null),J=S?!!S.closest("form"):!0,[G,se]=d.useState(new Set),U=Array.from(G).map(ne=>ne.props.value).join(";");return d.createElement(jd,x,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:b,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:B,open:O,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(ne=>{se(M=>new Set(M).add(ne))},[]),onNativeOptionRemove:d.useCallback(ne=>{se(M=>{const ee=new Set(M);return ee.delete(ne),ee})},[])},n)),J?d.createElement(f5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:ne=>B(ne.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(G)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Ue(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(x=>{const S=f().filter(b=>!b.disabled),E=S.find(b=>b.value===s.value),_=p5(S,x,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Ae.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const S=x.target;S.hasPointerCapture(x.pointerId)&&S.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const S=m.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&p(x.key),!(S&&x.key===" ")&&SG.includes(x.key)&&(y(),x.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Ue(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Ae.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Ae.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E,..._}=e,b=Fa(dc,n),[C,R]=d.useState(null),[P,O]=d.useState(null),A=Ue(t,fe=>R(fe)),[D,B]=d.useState(null),[V,J]=d.useState(null),G=og(n),[se,U]=d.useState(!1),ne=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const M=d.useCallback(fe=>{const[xe,...Re]=G().map(ze=>ze.ref.current),[Me]=Re.slice(-1),Oe=document.activeElement;for(const ze of fe)if(ze===Oe||(ze==null||ze.scrollIntoView({block:"nearest"}),ze===xe&&P&&(P.scrollTop=0),ze===Me&&P&&(P.scrollTop=P.scrollHeight),ze==null||ze.focus(),document.activeElement!==Oe))return},[G,P]),ee=d.useCallback(()=>M([D,C]),[M,D,C]);d.useEffect(()=>{se&&ee()},[se,ee]);const{onOpenChange:H,triggerPointerDownPosRef:X}=b;d.useEffect(()=>{if(C){let fe={x:0,y:0};const xe=Me=>{var Oe,ze,Mt,ct;fe={x:Math.abs(Math.round(Me.pageX)-((Oe=(ze=X.current)===null||ze===void 0?void 0:ze.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Me.pageY)-((Mt=(ct=X.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},Re=Me=>{fe.x<=10&&fe.y<=10?Me.preventDefault():C.contains(Me.target)||H(!1),document.removeEventListener("pointermove",xe),X.current=null};return X.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[C,H,X]),d.useEffect(()=>{const fe=()=>H(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[H]);const[W,le]=h5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),Re=xe.find(Oe=>Oe.ref.current===document.activeElement),Me=p5(xe,fe,Re);Me&&setTimeout(()=>Me.ref.current.focus())}),pe=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&(B(fe),Me&&(ne.current=!0))},[b.value]),$e=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ve=d.useCallback((fe,xe,Re)=>{const Me=!ne.current&&!Re;(b.value!==void 0&&b.value===xe||Me)&&J(fe)},[b.value]),We=r==="popper"?p2:LG,Ne=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:O,itemRefCallback:pe,selectedItem:D,onItemLeave:$e,itemTextRefCallback:Ve,focusSelectedItem:ee,selectedItemText:V,position:r,isPositioned:se,searchRef:W},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},_,Ne,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Me=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Me=Me.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,ze=Me.indexOf(Oe);Me=Me.slice(ze+1)}setTimeout(()=>M(Me)),fe.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ue(t,A=>m(A)),g=og(n),y=d.useRef(!1),x=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:b}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),B=i.valueNode.getBoundingClientRect(),V=_.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-D.left,ze=B.left-Oe,Mt=A.left-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=D.right-V.right,ze=window.innerWidth-B.right-Oe,Mt=window.innerWidth-A.right-ze,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(ze,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-hi*2,se=S.scrollHeight,U=window.getComputedStyle(f),ne=parseInt(U.borderTopWidth,10),M=parseInt(U.paddingTop,10),ee=parseInt(U.borderBottomWidth,10),H=parseInt(U.paddingBottom,10),X=ne+M+se+H+ee,W=Math.min(E.offsetHeight*5,X),le=window.getComputedStyle(S),pe=parseInt(le.paddingTop,10),$e=parseInt(le.paddingBottom,10),Ve=A.top+A.height/2-hi,We=G-Ve,Ne=E.offsetHeight/2,fe=E.offsetTop+Ne,xe=ne+M+fe,Re=X-xe;if(xe<=Ve){const Oe=E===J[J.length-1].ref.current;l.style.bottom="0px";const ze=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Ne+(Oe?$e:0)+ze+ee),ct=xe+Mt;l.style.height=ct+"px"}else{const Oe=E===J[0].ref.current;l.style.top="0px";const Mt=Math.max(Ve,ne+S.offsetTop+(Oe?pe:0)+Ne)+Re;l.style.height=Mt+"px",S.scrollTop=xe-Ve+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const O=d.useCallback(A=>{A&&x.current===!0&&(C(),b==null||b(),x.current=!1)},[C,b]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:O},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Ae.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,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)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Ue(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Ae.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,x=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(x,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Ae.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Ae.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),x=Ue(t,_=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(b=>{var C;return b||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Ae.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,E),onPointerMove:ue(s.onPointerMove,_=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,_=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Ue(t,_=>p(_),u.onItemTextChange,_=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,x=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(x),()=>E(x)),[S,E,x]),d.createElement(d.Fragment,null,d.createElement(Ae.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Ae.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Ue(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Ae.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Ae.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Ue(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,x]=d.useState(null),[S,E]=d.useState(null),[_,b]=d.useState(0),[C,R]=d.useState(0),[P,O]=d.useState(!1),[A,D]=d.useState(!1),B=Ue(t,J=>u(J)),V=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:O,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:b,onCornerHeightChange:R},d.createElement(Ae.div,Y({dir:V},s,{ref:B,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Ue(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(Ae.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Ue(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[x,S]=d.useState(null),E=Ue(t,B=>S(B)),_=d.useRef(null),b=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),O=Ft(u),A=sg(p,10);function D(B){if(_.current){const V=B.clientX-_.current.left,J=B.clientY-_.current.top;f({x:V,y:J})}}return d.useEffect(()=>{const B=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,R)};return document.addEventListener("wheel",B,{passive:!1}),()=>document.removeEventListener("wheel",B,{passive:!1})},[C,x,R,P]),d.useEffect(O,[r,O]),fc(x,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:O,onThumbPointerDown:Ft(l)},d.createElement(Ae.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,B=>{B.button===0&&(B.target.setPointerCapture(B.pointerId),_.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(B))}),onPointerMove:ue(e.onPointerMove,D),onPointerUp:ue(e.onPointerUp,B=>{const V=B.target;V.hasPointerCapture(B.pointerId)&&V.releasePointerCapture(B.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Ue(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Ae.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),x=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x,y:S})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Ae.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[x,S]=d.useState(w2),[E,_]=d.useState([]),[b,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=R;R>0&&(V=R-1),P(V),t(x,b[V].name)},[R,b]),Zn("right",()=>{let V=R;R{r||p(u)},[r,u]);const O=d.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const J=await Wj(x);_(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),d.useEffect(()=>{if(!r)return;(async()=>{try{let J=E;y&&(J=new kc(J,{keys:["name"]}).search(y).map(ne=>J[ne.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(se=>{const U=n,ne=se.height*(U/se.width);return{src:`${Ls}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(se.name)}&width=${Math.ceil(U)}&height=${Math.ceil(ne)}`,height:ne,width:U,name:se.name}});C(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[E,y,i,n,r]);const A=V=>{f(V.currentTarget.scrollTop)},D=({index:V})=>{o(),P(V),t(x,b[V].name)},B=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:B()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:x,onValueChange:V=>S(V),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:V=>{switch(V){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(V=>v.jsx(yo,{value:V,children:V},V))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:O,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=je.createContext(null),lg=()=>je.useContext(U5),OY=e=>{const{children:t,...n}=e;return je.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=je.useRef(e);t.current=e,je.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=je.useState(n._formState),u=je.useRef(!0),f=je.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=je.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),je.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=je.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=je.useState(n._getWatch(r,o));return je.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),je.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:je.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:je.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:x,valueAsNumber:S,mount:E,disabled:_}=e._f,b=ve(t,x);if(!E||_)return{};const C=s?s[0]:i,R=G=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(G)?"":G||""),C.reportValidity())},P={},O=Yx(i),A=Yd(i),D=O||A,B=(S||Gx(i))&&Ht(i.value)&&Ht(b)||Hp(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=Y5.bind(null,x,n,P),J=(G,se,U,ne=ui.maxLength,M=ui.minLength)=>{const ee=G?se:U;P[x]={type:G?ne:M,message:ee,ref:i,...V(G?ne:M,ee)}};if(o?!Array.isArray(b)||!b.length:l&&(!D&&(B||Fn(b))||Fo(b)&&!b||A&&!X5(s).isValid||O&&!Z5(s).isValid)){const{value:G,message:se}=np(l)?{value:!!l,message:l}:sl(l);if(G&&(P[x]={type:ui.required,message:se,ref:C,...V(ui.required,se)},!n))return R(se),P}if(!B&&(!Fn(m)||!Fn(p))){let G,se;const U=sl(p),ne=sl(m);if(!Fn(b)&&!isNaN(b)){const M=i.valueAsNumber||b&&+b;Fn(U.value)||(G=M>U.value),Fn(ne.value)||(se=Mnew Date(new Date().toDateString()+" "+W),H=i.type=="time",X=i.type=="week";Wo(U.value)&&b&&(G=H?ee(b)>ee(U.value):X?b>U.value:M>new Date(U.value)),Wo(ne.value)&&b&&(se=H?ee(b)+G.value,ne=!Fn(se.value)&&b.length<+se.value;if((U||ne)&&(J(U,G.message,se.message),!n))return R(P[x].message),P}if(g&&!B&&Wo(b)){const{value:G,message:se}=sl(g);if(Kp(G)&&!b.match(G)&&(P[x]={type:ui.pattern,message:se,ref:i,...V(ui.pattern,se)},!n))return R(se),P}if(y){if(ms(y)){const G=await y(b,t),se=$2(G,C);if(se&&(P[x]={...se,...V(ui.validate,se.message)},!n))return R(se.message),P}else if(sn(y)){let G={};for(const se in y){if(!Fr(G)&&!n)break;const U=$2(await y[se](b,t),C,se);U&&(G={...U,...V(se,U.message)},R(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:C,...G},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Z=>{clearTimeout(m),m=setTimeout(L,Z)},b=async L=>{if(p.isValid||L){const Z=n.resolver?Fr((await B()).errors):await J(o,!0);Z!==r.isValid&&g.state.next({isValid:Z})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Z=[],q,we,me=!0,de=!0)=>{if(we&&q){if(l.action=!0,de&&Array.isArray(ve(o,L))){const ke=q(ve(o,L),we.argA,we.argB);me&&wt(o,L,ke)}if(de&&Array.isArray(ve(r.errors,L))){const ke=q(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,ke),HY(r.errors,L)}if(p.touchedFields&&de&&Array.isArray(ve(r.touchedFields,L))){const ke=q(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,ke)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:se(L,Z),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Z)},P=(L,Z)=>{wt(r.errors,L,Z),g.state.next({errors:r.errors})},O=(L,Z,q,we)=>{const me=ve(o,L);if(me){const de=ve(s,L,Ht(q)?ve(i,L):q);Ht(de)||we&&we.defaultChecked||Z?wt(s,L,Z?de:I0(me._f)):M(L,de),l.mount&&b()}},A=(L,Z,q,we,me)=>{let de=!1,ke=!1;const ft={name:L};if(!q||we){p.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=se(),de=ke!==ft.isDirty);const ht=ma(ve(i,L),Z);ke=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,de=de||p.dirtyFields&&ke!==!ht}if(q){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,q),ft.touchedFields=r.touchedFields,de=de||p.touchedFields&&ht!==q)}return de&&me&&g.state.next(ft),de?ft:{}},D=(L,Z,q,we)=>{const me=ve(r.errors,L),de=p.isValid&&Fo(Z)&&r.isValid!==Z;if(e.delayError&&q?(f=_(()=>P(L,q)),f(e.delayError)):(clearTimeout(m),f=null,q?wt(r.errors,L,q):pn(r.errors,L)),(q?!ma(me,q):me)||!Fr(we)||de){const ke={...we,...de&&Fo(Z)?{isValid:Z}:{},errors:r.errors,name:L};r={...r,...ke},g.state.next(ke)}C(!1)},B=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async L=>{const{errors:Z}=await B(L);if(L)for(const q of L){const we=ve(Z,q);we?wt(r.errors,q,we):pn(r.errors,q)}else r.errors=Z;return Z},J=async(L,Z,q={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:de,...ke}=me;if(de){const ft=u.array.has(de.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Z,ft);if(ht[de.name]&&(q.valid=!1,Z))break;!Z&&(ve(ht,de.name)?ft?FY(r.errors,ht,de.name):wt(r.errors,de.name,ht[de.name]):pn(r.errors,de.name))}ke&&await J(ke,Z,q)}}return q.valid},G=()=>{for(const L of u.unMount){const Z=ve(o,L);Z&&(Z._f.refs?Z._f.refs.every(q=>!N0(q)):!N0(Z._f.ref))&&fe(L)}u.unMount=new Set},se=(L,Z)=>(L&&Z&&wt(s,L,Z),!ma(pe(),i)),U=(L,Z,q)=>K5(L,u,{...l.mount?s:Ht(Z)?i:Wo(L)?{[L]:Z}:Z},q,Z),ne=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),M=(L,Z,q={})=>{const we=ve(o,L);let me=Z;if(we){const de=we._f;de&&(!de.disabled&&wt(s,L,e3(Z,de)),me=Hp(de.ref)&&Fn(Z)?"":Z,q5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=me.includes(ke.value)):de.refs?Yd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(me)?!!me.find(ft=>ft===ke.value):me===ke.value)):de.refs[0]&&(de.refs[0].checked=!!me):de.refs.forEach(ke=>ke.checked=ke.value===me):Gx(de.ref)?de.ref.value="":(de.ref.value=me,de.ref.type||g.values.next({name:L,values:{...s}})))}(q.shouldDirty||q.shouldTouch)&&A(L,me,q.shouldTouch,q.shouldDirty,!0),q.shouldValidate&&le(L)},ee=(L,Z,q)=>{for(const we in Z){const me=Z[we],de=`${L}.${we}`,ke=ve(o,de);(u.array.has(L)||!Gp(me)||ke&&!ke._f)&&!$l(me)?ee(de,me,q):M(de,me,q)}},H=(L,Z,q={})=>{const we=ve(o,L),me=u.array.has(L),de=so(Z);wt(s,L,de),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&q.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:se(L,de)})):we&&!we._f&&!Fn(de)?ee(L,de,q):M(L,de,q),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},X=async L=>{const Z=L.target;let q=Z.name,we=!0;const me=ve(o,q),de=()=>Z.type?I0(me._f):z5(L),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,q,ft)};if(me){let ft,ht;const _n=de(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,q)&&!me._f.deps||WY(Cr,ve(r.touchedFields,q),r.isSubmitted,S,x),Co=S2(q,u,Cr);wt(s,q,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(q,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:q,type:L.type,values:{...s}}),Ni)return p.isValid&&b(),Ba&&g.state.next({name:q,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await B([q]);if(ke(_n),we){const Ws=k2(r.errors,o,q),Ii=k2(Di,o,Ws.name||q);ft=Ii.error,q=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[q],ke(_n),we&&(ft?ht=!1:p.isValid&&(ht=await J(o,!0)));we&&(me._f.deps&&le(me._f.deps),D(q,ht,ft,Vn))}},W=(L,Z)=>{if(ve(r.errors,Z)&&L.focus)return L.focus(),1},le=async(L,Z={})=>{let q,we;const me=ep(L);if(C(!0),n.resolver){const de=await V(Ht(L)?L:me);q=Fr(de),we=L?!me.some(ke=>ve(de,ke)):q}else L?(we=(await Promise.all(me.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=q=await J(o);return g.state.next({...!Wo(L)||p.isValid&&q!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:q}:{},errors:r.errors,isValidating:!1}),Z.shouldFocus&&!we&&tp(o,W,L?me:u.mount),we},pe=L=>{const Z={...i,...l.mount?s:{}};return Ht(L)?Z:Wo(L)?ve(Z,L):L.map(q=>ve(Z,q))},$e=(L,Z)=>({invalid:!!ve((Z||r).errors,L),isDirty:!!ve((Z||r).dirtyFields,L),isTouched:!!ve((Z||r).touchedFields,L),error:ve((Z||r).errors,L)}),Ve=L=>{L&&ep(L).forEach(Z=>pn(r.errors,Z)),g.state.next({errors:L?r.errors:{}})},We=(L,Z,q)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Z,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),q&&q.shouldFocus&&we&&we.focus&&we.focus()},Ne=(L,Z)=>ms(L)?g.values.subscribe({next:q=>L(U(void 0,Z),q)}):U(L,Z,!0),fe=(L,Z={})=>{for(const q of L?ep(L):u.mount)u.mount.delete(q),u.array.delete(q),Z.keepValue||(pn(o,q),pn(s,q)),!Z.keepError&&pn(r.errors,q),!Z.keepDirty&&pn(r.dirtyFields,q),!Z.keepTouched&&pn(r.touchedFields,q),!n.shouldUnregister&&!Z.keepDefaultValue&&pn(i,q);g.values.next({values:{...s}}),g.state.next({...r,...Z.keepDirty?{isDirty:se()}:{}}),!Z.keepIsValid&&b()},xe=({disabled:L,name:Z,field:q,fields:we,value:me})=>{if(Fo(L)){const de=L?void 0:Ht(me)?I0(q?q._f:ve(we,Z)._f):me;wt(s,Z,de),A(Z,de,!1,!1,!0)}},Re=(L,Z={})=>{let q=ve(o,L);const we=Fo(Z.disabled);return wt(o,L,{...q||{},_f:{...q&&q._f?q._f:{ref:{name:L}},name:L,mount:!0,...Z}}),u.mount.add(L),q?xe({field:q,disabled:Z.disabled,name:L}):O(L,!0,Z.value),{...we?{disabled:Z.disabled}:{},...n.progressive?{required:!!Z.required,min:du(Z.min),max:du(Z.max),minLength:du(Z.minLength),maxLength:du(Z.maxLength),pattern:du(Z.pattern)}:{},name:L,onChange:X,onBlur:X,ref:me=>{if(me){Re(L,Z),q=ve(o,L);const de=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,ke=BY(de),ft=q._f.refs||[];if(ke?ft.find(ht=>ht===de):de===q._f.ref)return;wt(o,L,{_f:{...q._f,...ke?{refs:[...ft.filter(N0),de,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:de.type,name:L}}:{ref:de}}}),O(L,!1,void 0,de)}else q=ve(o,L,{}),q._f&&(q._f.mount=!1),(n.shouldUnregister||Z.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Me=()=>n.shouldFocusError&&tp(o,W,u.mount),Oe=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Z=>{Z.disabled=L},0,!1))},ze=(L,Z)=>async q=>{q&&(q.preventDefault&&q.preventDefault(),q.persist&&q.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:de}=await B();r.errors=me,we=de}else await J(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,q)):(Z&&await Z({...r.errors},q),Me(),setTimeout(Me)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Z={})=>{ve(o,L)&&(Ht(Z.defaultValue)?H(L,ve(i,L)):(H(L,Z.defaultValue),wt(i,L,Z.defaultValue)),Z.keepTouched||pn(r.touchedFields,L),Z.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Z.defaultValue?se(L,ve(i,L)):se()),Z.keepError||(pn(r.errors,L),p.isValid&&b()),g.state.next({...r}))},ct=(L,Z={})=>{const q=L?so(L):i,we=so(q),me=L&&!Fr(L)?we:i;if(Z.keepDefaultValues||(i=q),!Z.keepValues){if(Z.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(me,de,ve(s,de)):H(de,ve(me,de));else{if(Wx&&Ht(L))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Z.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Z.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Z.keepSubmitCount?r.submitCount:0,isDirty:Z.keepDirty?r.isDirty:!!(Z.keepDefaultValues&&!ma(L,i)),isSubmitted:Z.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z.keepDirtyValues?r.dirtyFields:Z.keepDefaultValues&&L?D0(i,L):{},touchedFields:Z.keepTouched?r.touchedFields:{},errors:Z.keepErrors?r.errors:{},isSubmitSuccessful:Z.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Z)=>ct(ms(L)?L(s):L,Z);return{control:{register:Re,unregister:fe,getFieldState:$e,handleSubmit:ze,setError:We,_executeSchema:B,_getWatch:U,_getDirty:se,_updateValid:b,_removeUnmounted:G,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:ne,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Oe,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:le,register:Re,handleSubmit:ze,watch:Ne,setValue:H,getValues:pe,reset:Kt,resetField:Mt,clearErrors:Ve,unregister:fe,setError:We,setFocus:(L,Z={})=>{const q=ve(o,L),we=q&&q._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Z.shouldSelect&&me.select())}},getFieldState:$e}}function YY(e={}){const t=je.useRef(),n=je.useRef(),[r,o]=je.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),je.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),je.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),je.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),je.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},he=mt.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"]);class Go extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case he.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case he.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case he.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case he.invalid_union:n="Invalid input";break;case he.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case he.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case he.invalid_arguments:n="Invalid function arguments";break;case he.invalid_return_type:n="Invalid function return type";break;case he.invalid_date:n="Invalid date";break;case he.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case he.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case he.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case he.custom:n="Invalid input";break;case he.invalid_intersection_types:n="Intersection results could not be merged";break;case he.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case he.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var De;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(De||(De={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const O2=(e,t)=>{if(Zp(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:he.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:Be.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:Be.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:Be.ZodDefault})}brand(){return new hX({typeName:Be.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:Be.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:he.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:he.invalid_string,...De.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...De.errToObj(t)})}url(t){return this._addCheck({kind:"url",...De.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...De.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...De.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...De.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...De.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...De.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...De.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...De.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...De.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...De.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...De.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...De.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...De.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...De.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...De.errToObj(n)})}nonempty(t){return this.min(1,De.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new yi({checks:[],typeName:Be.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:De.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:De.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:De.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:De.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew hc({checks:[],typeName:Be.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:he.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,De.toString(n))}gt(t,n){return this.setLimit("min",t,!1,De.toString(n))}lte(t,n){return this.setLimit("max",t,!0,De.toString(n))}lt(t,n){return this.setLimit("max",t,!1,De.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:De.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:De.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:De.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:De.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:De.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:De.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pc({checks:[],typeName:Be.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:Be.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:he.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:he.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:De.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:De.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Be.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:Be.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:Be.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:Be.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:Be.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:Be.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:he.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:Be.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:Be.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:he.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:he.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,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:De.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:De.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:De.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Be.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:he.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:he.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return De.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=De.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Be.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:Be.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:he.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:he.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:Be.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:he.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:he.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:Be.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:he.invalid_intersection_types}),Ze)};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}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:Be.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:he.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:he.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:Be.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:he.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:Be.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:Be.ZodRecord,...Xe(n)})}}class O1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:he.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:Be.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:he.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:he.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:De.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:De.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:Be.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:he.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:he.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:Be.ZodFunction,...Xe(r)})}}class nm extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}nm.create=(e,t)=>new nm({getter:e,typeName:Be.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:he.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:Be.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:Be.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:he.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:he.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:he.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:he.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:Be.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:he.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:Be.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Be.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:Be.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:Be.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:Be.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:Be.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:Be.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:Be.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:he.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:Be.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:Be.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:Be.ZodReadonly,...Xe(t)});Vt.lazycreate;var Be;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(Be||(Be={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Ae.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Ae.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Ue(t,b=>g(b)),x=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Ae.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:ue(e.onClick,b=>{_(C=>!C),S&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!x.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Ae.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Ue(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Ue(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(M=>[M.updateAppState,M.settings,M.updateSettings,M.fileManagerState,M.setModel,M.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,x]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_,refetch:b}=ML({queryKey:["serverConfig"],queryFn:gT}),C=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),C.setValue("removeBGModel",E.removeBGModel),C.setValue("realesrganModel",E.realesrganModel),C.setValue("interactiveSegModel",E.interactiveSegModel))},[C,E]);async function R(M){s({enableDownloadMask:M.enableDownloadMask,enableManualInpainting:M.enableManualInpainting,enableUploadMask:M.enableUploadMask,enableAutoExtractPrompt:M.enableAutoExtractPrompt});const ee=p.name!==i.model.name,H=(E==null?void 0:E.removeBGModel)!==M.removeBGModel&&A,X=(E==null?void 0:E.realesrganModel)!==M.realesrganModel&&D,W=(E==null?void 0:E.interactiveSegModel)!==M.interactiveSegModel&&B;if(ee||H||X||W){const pe=[];if(ee&&pe.push(`Switching model from ${i.model.name} to ${p.name}`),H&&pe.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${M.removeBGModel}`),X&&pe.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${M.realesrganModel}`),W&&pe.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${M.interactiveSegModel}`),x(pe),o({disableShortCuts:!0}),ee)try{const $e=await Bj(p.name);m({title:`Switch to ${$e.name} success`}),u(p)}catch($e){m({variant:"destructive",title:`Switch to ${p.name} failed: ${$e}`}),g(i.model)}if(H)try{const $e=await v0(Ao.RemoveBG,M.removeBGModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch RemoveBG model to ${M.removeBGModel} failed: ${$e}`})}if(X)try{const $e=await v0(Ao.RealESRGAN,M.realesrganModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch RealESRGAN model to ${M.realesrganModel} failed: ${$e}`})}if(W)try{const $e=await v0(Ao.InteractiveSeg,M.interactiveSegModel);if($e.status!==200)throw new Error($e.statusText)}catch($e){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${M.interactiveSegModel} failed: ${$e}`})}x([]),o({disableShortCuts:!1}),b()}}if(Zn("s",()=>{t(),e&&R(C.getValues())},[e,C,p,E]),_!=="success")return v.jsx(v.Fragment,{});const P=E.modelInfos,O=E.plugins,A=O.some(M=>M.name===Ao.RemoveBG),D=O.some(M=>M.name===Ao.RealESRGAN),B=O.some(M=>M.name===Ao.InteractiveSeg);function V(M){t(),M||R(C.getValues())}function J(M){g(M)}function G(M){return P?P.filter(ee=>M.includes(ee.model_type)).map(ee=>v.jsxs("div",{onClick:()=>J(ee),className:"px-2",children:[v.jsx("div",{className:Ce([ee.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:ee.name})}),v.jsx(gn,{className:"my-1"})]},ee.name)):v.jsx("div",{children:"Please download model first"})}function se(){let M=fs;for(let ee of P)if(p.name===ee.name){M=ee.model_type,M===oC&&(M=uh),M===iC&&(M=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:M,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:G([fs])}),v.jsx(Su,{value:uh,children:G([uh,oC])}),v.jsx(Su,{value:dh,children:G([dh,iC])}),v.jsx(Su,{value:d0,children:G([d0])})]})]})]})]})}function U(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"enableManualInpainting",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableDownloadMask",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"enableAutoExtractPrompt",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:M.value,onCheckedChange:M.onChange})})]})})]})}function ne(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:C.control,name:"removeBGModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"realesrganModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:C.control,name:"interactiveSegModel",render:({field:M})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:M.onChange,defaultValue:M.value,disabled:!B,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(ee=>v.jsx(yo,{value:ee,children:ee},ee))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((M,ee)=>v.jsx("div",{children:M},ee))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(Jm,{open:e,onOpenChange:V,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:M=>M.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(M=>v.jsx(wn,{variant:"ghost",onClick:()=>r(M),className:Ce(n===M?"bg-muted ":"hover:bg-muted","justify-start"),children:M},M))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...C,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:C.handleSubmit(R),children:[n===F1?se():v.jsx(v.Fragment,{}),n===S3?U():v.jsx(v.Fragment,{}),n===_3?ne():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>V(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(O=>[O.file,O.customMask,O.isInpainting,O.serverConfig,O.runMannually(),O.settings.enableUploadMask,O.settings.model,O.setFile,O.setCustomFile,O.runInpainting,O.showPrevMask,O.hidePrevMask,O.imageHeight,O.imageWidth]),{toast:x}=Id(),[S,E]=Px(t),[_,b]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(O,A)=>{try{const D=await Vj(O,A);l(D)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:O=>{l(O)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async O=>{let A=null;try{A=await gF(O)}catch(D){x({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(O),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var x=l+m*y,S=u+p*y,E=f+g*y;i(x,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),x=j1(t,u-g,m+g,r);return{x:y,y:x}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,x=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,b=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,b,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(f,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,x=u-o,S=m*m+p*p,E=Math.sqrt(S)/x;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,b=E.lockAxisX,C=S.animationType,R=x.sizeX,P=x.sizeY,O=x.velocityAlignmentTime,A=O,D=kZ(e,u),B=Math.max(D,A),V=sm(e,R),J=sm(e,P),G=V*o.offsetWidth/100,se=J*o.offsetHeight/100,U=f+G,ne=m-G,M=p+se,ee=g-se,H=e.transformState,X=new Date().getTime();$3(e,C,B,function(W){var le=e.transformState,pe=le.scale,$e=le.positionX,Ve=le.positionY,We=new Date().getTime()-X,Ne=We/A,fe=E3[x.animationType],xe=1-fe(Math.min(1,Ne)),Re=1-W,Me=$e+s*Re,Oe=Ve+l*Re,ze=I2(Me,H.positionX,$e,b,y,m,f,ne,U,xe),Mt=I2(Oe,H.positionY,Ve,_,y,g,p,ee,M,xe);($e!==Me||Ve!==Oe)&&e.setTransformState(pe,ze,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,S=Qx(e,s,y,x);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,S=p.size,E=p.disabled,_=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=x?b*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var O=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,B=f&&D,V=fg(e,A.x,A.y,P,O,B),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var x=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,x,E),b=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,b,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,x=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var b=N3(t,i,s),C=Qx(e,_,b.x,b.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,x,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=je.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=je.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),je.createElement(Jx.Provider,{value:n},r)});je.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),je.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,x=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,b=E.current;return _!==null&&b!==null&&y&&(y==null||y(_,b)),function(){x==null||x()}},[]),je.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),je.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[S,E]=d.useState(null),_=Ue(t,U=>E(U)),b=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,O=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:U=>{var ne;(ne=[...b.current][C.current])===null||ne===void 0||ne.focus(),p(U)}}),B=d.useRef(A);function V(U){const ne=Pq(A,U);se(U,ne)}function J(U){se(U,C.current)}function G(){const U=B.current[C.current];A[C.current]!==U&&g(A)}function se(U,ne,{commit:M}={commit:!1}){const ee=Nq(i),H=Dq(Math.round((U-r)/i)*i+r,ee),X=fd(H,[r,o]);D((W=[])=>{const le=kq(W,X,ne);if(Oq(le,u*i)){C.current=le.indexOf(X);const pe=String(le)!==String(W);return pe&&M&&g(le),pe?le:W}else return W})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:b.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(O,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:_,onPointerDown:ue(x.onPointerDown,()=>{l||(B.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&se(r,0,{commit:!0}),onEndKeyDown:()=>!l&&se(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:ne})=>{if(!l){const H=L3.includes(U.key)||U.shiftKey&&F3.includes(U.key)?10:1,X=C.current,W=A[X],le=i*H*ne;se(W+le,X,{commit:!0})}}})))),P&&A.map((U,ne)=>d.createElement(Rq,{key:ne,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Ue(t,C=>g(C)),x=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function b(C){const R=x.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return x.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=b(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=b(C.clientX);l==null||l(R)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Ue(t,m),g=d.useRef(),y=!o;function x(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=x(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=x(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Ae.span,Y({},f,{ref:t,onKeyDown:ue(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:ue(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:ue(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:ue(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Ae.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Ue(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Ae.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Ue(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Ue(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),x=m==null?void 0:m[s.size],S=x?Aq(x,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Ae.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:x},S,E,_,b,C,R]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,O]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),B=()=>{},V=(W,le)=>W2(W,le,p,y,n,o),J=(W,le)=>W2(W,le,g,x,t,r),G=W=>{if(f)return;const le=W.clientX,pe=W.clientY,$e=Math.round((pe-A.startResizeY)/i),Ve=Math.round((le-A.startResizeX)/i),We=()=>{const Re=A.initHeight-$e,Me=A.initY+$e,[Oe,ze]=J(Me,Re);b(ze),E(Oe)},Ne=()=>{const Re=A.initHeight+$e,[Me,Oe]=J(A.initY,Re);b(Oe),E(Me)},fe=()=>{const Re=A.initWidth-Ve,Me=A.initX+Ve,[Oe,ze]=V(Me,Re);_(ze),S(Oe)},xe=()=>{const Re=A.initWidth+Ve,[Me,Oe]=V(A.initX,Re);_(Oe),S(Me)};if(C)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Ne(),fe();break}case"bottomright":{Ne(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Ne();break}case"left":{fe();break}}if(P){const Re=A.initX+Ve,Me=A.initY+$e,[Oe,ze]=V(Re,A.initWidth),[Mt,ct]=J(Me,A.initHeight);_(ze),b(ct),S(Oe),E(Mt)}},se=()=>{C&&R(!1),P&&O(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",G,ll),document.addEventListener("pointerup",se,ll),document.addEventListener("pointercancel",se,ll),()=>{document.removeEventListener("pointermove",G,ll),document.removeEventListener("pointerup",se,ll),document.removeEventListener("pointercancel",se,ll)}},[C,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(R(!0),D({initX:p,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},ne=(W,le,pe)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ne="0",fe="0",xe=pe,Re="-6px";return pe===""&&(Re="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Ne="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:Re,transform:`translate(${Ne}, ${fe}) scale(${1/i})`},"data-ord":le+pe,"aria-label":le+pe,tabIndex:-1,role:"button"})},M=()=>v.jsxs("div",{onFocus:B,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),ne("cursor-nw-resize","top","left"),ne("cursor-ne-resize","top","right"),ne("cursor-sw-resize","bottom","left"),ne("cursor-se-resize","bottom","right"),ne("cursor-ns-resize","top",""),ne("cursor-ns-resize","bottom",""),ne("cursor-ew-resize","left",""),ne("cursor-ew-resize","right","")]}),ee=W=>{O(!0),D({initX:p,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},H=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ee,children:[y," x ",x]}),X=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:p,top:g},children:[X(),H(),M()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,x,S,E,_,b,C]=bt(ee=>[ee.isInpainting,ee.imageHeight,ee.imageWidth,ee.isSD(),ee.extenderState,ee.setExtenderX,ee.setExtenderY,ee.setExtenderWidth,ee.setExtenderHeight,ee.settings.extenderDirection,ee.isCropperExtenderResizing,ee.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),O=()=>{},A=(ee,H)=>H2(ee,H,f,n),D=(ee,H)=>H2(ee,H,m,t),B=ee=>{if(i)return;const H=ee.clientX,X=ee.clientY,W=Math.round((X-R.startResizeY)/r),le=Math.round((H-R.startResizeX)/r),pe=()=>{const Ne=R.initHeight-W,fe=R.initY+W;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initHeight-Math.abs(R.initY));else{const Me=D(fe,Ne);xe=Me[0],Re=Me[1]}E(Re),x(xe)},$e=()=>{const Ne=R.initHeight+W;let[fe,xe]=D(R.initY,Ne);_===Ln.xy&&xe{const Ne=R.initWidth-le,fe=R.initX+le;let xe=fe,Re=Ne;if(_===Ln.xy)xe>0&&(xe=0,Re=R.initWidth-Math.abs(R.initX));else{const Me=A(fe,Ne);xe=Me[0],Re=Me[1]}S(Re),y(xe)},We=()=>{const Ne=R.initWidth+le;let[fe,xe]=A(R.initX,Ne);_===Ln.xy&&xe{b&&C(!1)};d.useEffect(()=>{if(b)return document.addEventListener("pointermove",B,cl),document.addEventListener("pointerup",V,cl),document.addEventListener("pointercancel",V,cl),()=>{document.removeEventListener("pointermove",B,cl),document.removeEventListener("pointerup",V,cl),document.removeEventListener("pointercancel",V,cl)}},[b,p,g,R]);const J=ee=>{const{ord:H}=ee.target.dataset;H&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:H}))},G=(ee,H,X)=>{const pe="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let $e="0",Ve="0",We=X,Ne="-6px";return X===""&&(Ne="50%",H==="left"||H==="right"?(We="top",Ve="-50%"):(We="left",$e="-50%")),v.jsx("div",{className:Ce(pe,ee),style:{[H]:-6,[We]:Ne,transform:`translate(${$e}, ${Ve}) scale(${1/r})`},"data-ord":H+X,"aria-label":H+X,tabIndex:-1,role:"button"})},se=()=>v.jsxs("div",{onFocus:O,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ee=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ee.clientX,startResizeY:ee.clientY,ord:""})},ne=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[p," x ",g]}),M=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[M(),ne(),se()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,x,S,E,_,b,C,R,P,O,A,D]=bt(K=>[K.disableShortCuts,K.windowSize,K.isInpainting,K.imageWidth,K.imageHeight,K.settings,K.serverConfig.enableAutoSaving,K.setImageSize,K.setBaseBrushSize,K.interactiveSegState,K.updateInteractiveSegState,K.handleCanvasMouseDown,K.handleCanvasMouseMove,K.undo,K.redo,K.undoDisabled(),K.redoDisabled(),K.getIsProcessing(),K.updateAppState,K.runMannually(),K.runInpainting,K.isCropperExtenderResizing]),B=bt(K=>K.editorState.baseBrushSize),V=bt(K=>K.getBrushSize()),J=bt(K=>K.editorState.renders),G=bt(K=>K.editorState.extraMasks),se=bt(K=>K.editorState.temporaryMasks),U=bt(K=>K.editorState.lineGroups),ne=bt(K=>K.editorState.curLineGroup),[M,ee]=d.useState(!1),[H,X]=Px(t),[W,le]=d.useState(),[pe,$e]=d.useState(),[{x:Ve,y:We},Ne]=d.useState({x:-1,y:-1}),[fe,xe]=d.useState(!1),[Re,Me]=d.useState(!1),[Oe,ze]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Z=o.height/2,q=d.useRef(null),[we,me]=d.useState(!1),[de,ke]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>ne.length!==0,[ne]);d.useEffect(()=>{if(!pe||!X||s===0||l===0)return;const K=J.length===0?H:J[J.length-1];pe.canvas.width=s,pe.canvas.height=l,pe.clearRect(0,0,pe.canvas.width,pe.canvas.height),pe.drawImage(K,0,0,s,l)},[J,H,X,pe,l,s]),d.useEffect(()=>{!W||!X||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),se.forEach(K=>{W.drawImage(K,0,0,s,l)}),G.forEach(K=>{W.drawImage(K,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(W,ne))},[se,G,X,g,W,ne,l,s]);const Cr=d.useCallback(async()=>{let K=t;if(J.length>0){const Ye=J[J.length-1];K=await Nu(Ye.currentSrc,t.name,t.type)}return K},[t,J]),Ni=()=>J.length!==0,Co=d.useCallback(()=>{let K=512,Ye=512;return X?(J.length===0?(K=H.naturalWidth,Ye=H.naturalHeight):J.length!==0&&(K=J[J.length-1].width,Ye=J[J.length-1].height),[K,Ye]):[K,Ye]},[H,X,J]);d.useEffect(()=>{var tf;if(!X)return;const[K,Ye]=Co();(K!==s||Ye!==l)&&m(K,Ye);const st=o.width/K,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${K}x${Ye}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),K!=W.canvas.width&&(W.canvas.width=K),Ye!=W.canvas.height&&(W.canvas.height=Ye)),we||((tf=q.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[q,l,s,H,X,o,we,Co]),d.useEffect(()=>{var K;console.log("[useEffect] centerView"),(K=q==null?void 0:q.current)==null||K.centerView(gt,1)},[l,s,q,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const K=q.current;if(!K)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;K.setTransform(Ye,st,gt,200,"easeOutQuad"),K.instance.transformState.scale&&(K.instance.transformState.scale=gt),ct(gt),Er(!1)},[q,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(de?ke(!1):Vn())},[de,i,Vn]);const Di=K=>{const Ye=K.nativeEvent;Ne({x:Ye.pageX,y:Ye.pageY})},Ws=K=>{R||g.isInteractiveSeg||Oe||de&&ne.length!==0&&S(f0(K))},Ii=async K=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,K),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=K=>{if(dC(K)){ze(!1);return}!_n()||g.isInteractiveSeg||Oe||!H.src||!(W!=null&&W.canvas)||i||de&&(O?ke(!1):A())},bg=K=>{if(g.isInteractiveSeg){const Ye=f0(K),st=[...g.clicks];uC(K)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=K=>{if(!(R||g.isInteractiveSeg||Oe||!X||!(W!=null&&W.canvas))&&!uC(K)){if(dC(K)){ze(!0);return}ke(!0),x(f0(K))}},Jd=K=>{K.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=K=>{K.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},K=>{K==null||K.preventDefault(),K==null||K.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&J.length>0){try{await Hj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const K=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=J[J.length-1];if(bF(Ye.currentSrc,K),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,J,u,l,s,U]);Zn("meta+s,ctrl+s",Nc);const Dc=K=>{K!==fe&&!Oe&&!D&&xe(K)},_g=d.useCallback(()=>{if(R)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,R]);Zn("[",()=>{let K=B;B>10&&(K=B-10),B<=10&&B>0&&(K=B-5),p(K)},[B]),Zn("]",()=>{p(B+10)},[B]),Zn("shift+r",()=>{O&&_n()&&A()},[O,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&J.length>0&&W!=null&&W.canvas&&(await xF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),s2(" ",K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!1),ze(!0))},K=>{r||(K==null||K.preventDefault(),K==null||K.stopPropagation(),xe(!0),ze(!1))});const Ic=()=>{var Ye,st,Qr,an;let K=gt;return((st=(Ye=q.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(K=(an=(Qr=q.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),K},ef=(K,Ye)=>{const st=Ic();return{width:`${V*st}px`,height:`${V*st}px`,left:`${K}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=K=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:K}),Eg=K=>{p(K),Re||(Me(!0),window.setTimeout(()=>{Me(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ve}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:K=>{K&&(q.current=K)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:K=>{ct(K.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:K=>{if(K&&!pe){const Ye=K.getContext("2d");Ye&&$e(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:K=>{K.preventDefault()},onMouseOver:()=>{Dc(!0),Me(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:K=>{if(K&&!W){const Ye=K.getContext("2d");Ye&&le(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:M&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:H.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),fe&&!i&&!Oe&&(g.isInteractiveSeg?Cg():Lc(ef(Ve,We))),Re&&Lc(ef(L,Z)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[B],onValueChange:K=>Eg(K[0]),onClick:()=>Me(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:b,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:K=>{K.preventDefault(),ee(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ee(!1)},mu)},disabled:J.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!J.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Ue(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,...S}=e,E=Us(bo,n),_=Qd(bo,n),b=gg(n),C=Y3(n),R=nQ(n),[P,O]=d.useState(null),A=d.useRef(null),D=Ue(t,A,E.onContentChange),B=d.useRef(0),V=d.useRef(""),J=d.useRef(0),G=d.useRef(null),se=d.useRef("right"),U=d.useRef(0),ne=x?qm:d.Fragment,M=x?{as:Zo,allowPinchZoom:!0}:void 0,ee=X=>{var W,le;const pe=V.current+X,$e=R().filter(Re=>!Re.disabled),Ve=document.activeElement,We=(W=$e.find(Re=>Re.ref.current===Ve))===null||W===void 0?void 0:W.textValue,Ne=$e.map(Re=>Re.textValue),fe=kQ(Ne,pe,We),xe=(le=$e.find(Re=>Re.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function Re(Me){V.current=Me,window.clearTimeout(B.current),Me!==""&&(B.current=window.setTimeout(()=>Re(""),1e3))})(pe),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(B.current),[]),Xm();const H=d.useCallback(X=>{var W,le;return se.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(X,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return d.createElement(lQ,{scope:n,searchRef:V,onItemEnter:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),onItemLeave:d.useCallback(X=>{var W;H(X)||((W=A.current)===null||W===void 0||W.focus(),O(null))},[H]),onTriggerLeave:d.useCallback(X=>{H(X)&&X.preventDefault()},[H]),pointerGraceTimerRef:J,onPointerGraceIntentChange:d.useCallback(X=>{G.current=X},[])},d.createElement(ne,M,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,X=>{var W;X.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:O,onEntryFocus:ue(u,X=>{_.isUsingKeyboardRef.current||X.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},b,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,X=>{const le=X.target.closest("[data-radix-menu-content]")===X.currentTarget,pe=X.ctrlKey||X.altKey||X.metaKey,$e=X.key.length===1;le&&(X.key==="Tab"&&X.preventDefault(),!pe&&$e&&ee(X.key));const Ve=A.current;if(X.target!==Ve||!Jq.includes(X.key))return;X.preventDefault();const Ne=R().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);K3.includes(X.key)&&Ne.reverse(),$Q(Ne)}),onBlur:ue(e.onBlur,X=>{X.currentTarget.contains(X.target)||(window.clearTimeout(B.current),V.current="")}),onPointerMove:ue(e.onPointerMove,gd(X=>{const W=X.target,le=U.current!==X.clientX;if(X.currentTarget.contains(W)&&le){const pe=X.clientX>U.current?"right":"left";se.current=pe,U.current=X.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Ue(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:ue(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Ue(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const x=u.current;if(x){var S;y(((S=x.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Ae.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:ue(e.onPointerMove,gd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,gd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>p(!0)),onBlur:ue(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Ae.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Ae.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:ue(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const S=(x=n.content)===null||x===void 0?void 0:x.dataset.side,E=S==="right",_=E?-5:5,b=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x:b,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x:b,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Ue(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:ue(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Ae.button,Y({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:Nm(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(M=>[M.serverConfig.samplers,M.settings,M.paintByExampleFile,M.getIsProcessing(),M.updateSettings,M.runInpainting,M.updateAppState,M.updateExtenderByBuiltIn,M.updateExtenderDirection,M.adjustMask,M.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=M=>{M.key==="Enter"&&M.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:M=>{o({showCropper:M}),M&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:M=>{o({enableControlnet:M})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:M=>o({controlnetConditioningScale:M[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:M=>{o({controlnetConditioningScale:M})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:M=>{o({controlnetMethod:M})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(M=>v.jsx(yo,{value:M,children:M.split("/")[1]},M))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:M=>{o({enableLCMLora:M})}})]}),v.jsx(gn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:M=>{o({enableFreeu:M})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,s2:M}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b1:M}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:M=>{o({freeuConfig:{...t.freeuConfig,b2:M}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:M=>{M.preventDefault(),M.stopPropagation();const ee=M.target;o({negativePrompt:ee.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:M=>{s({paintByExampleFile:M})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:M=>o({p2pImageGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({p2pImageGuidanceScale:M})}})]})]}),O=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:M=>o({sdStrength:M[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:M=>{o({sdStrength:M})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:M=>{o({showExtender:M}),M&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:M=>{u(M)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(M=>v.jsx(yo,{value:M,children:M},M))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:M=>{o({powerpaintTask:M})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(M=>v.jsx(yo,{value:M,children:M},M))})})]})]}),B=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:M=>o({sdSteps:M[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:M=>{o({sdSteps:M})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:M=>o({sdGuidanceScale:M[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:M=>{o({sdGuidanceScale:M})}})]})]}),J=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:M=>{o({sdSampler:M})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(M=>v.jsx(yo,{value:M,className:"text-xs",children:M},M))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:M=>{o({seedFixed:M})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:M=>{o({seed:M})}})]})]}),se=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:M=>o({sdMaskBlur:M[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:M=>{o({sdMaskBlur:M})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:M=>{o({sdMatchHistograms:M})}})]}),v.jsx(gn,{})]}),ne=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:M=>o({adjustMaskKernelSize:M[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:M=>{o({adjustMaskKernelSize:M})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),ne(),D(),B(),V(),P(),O(),J(),G(),C(),v.jsx(gn,{}),E(),_(),se(),U(),b(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=TA()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Xo extends qt{constructor(t,n){super(),vg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=r$?{}:RA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{n$&&this.ws.send(i)}catch{}o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=X1(n.host).host),vg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=$A,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){hl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ac.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,vg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){lb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new NA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Ae.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Ae.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Ue(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;d.useEffect(()=>{const E=_=>{var b;r.every(R=>_[R]||_.code===R)&&((b=p.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(x&&E&&_){const b=()=>{if(!s.isClosePausedRef.current){const O=new CustomEvent(ew);_.dispatchEvent(O),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const O=new CustomEvent(tw);_.dispatchEvent(O),s.isClosePausedRef.current=!1}},R=O=>{!E.contains(O.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",b),E.addEventListener("focusout",R),E.addEventListener("pointermove",b),E.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",b),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",b),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",C)}}},[x,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const b=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?b.reverse():b).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=b=>{const C=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!C){const D=document.activeElement,B=b.shiftKey;if(b.target===E&&B){var P;(P=f.current)===null||P===void 0||P.focus();return}const G=S({tabbingDirection:B?"backwards":"forwards"}),se=G.findIndex(U=>U===D);if(U0(G.slice(se+1)))b.preventDefault();else{var O,A;B?(O=f.current)===null||O===void 0||O.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Ae.ol,Y({tabIndex:-1},i,{ref:g}))),x&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:ue(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...x}=e,S=wg(xg,n),[E,_]=d.useState(null),b=Ue(t,U=>_(U)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,O=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:B,onToastRemove:V}=S,J=Ft(()=>{var U;(E==null?void 0:E.contains(document.activeElement))&&((U=S.viewport)===null||U===void 0||U.focus()),s()}),G=d.useCallback(U=>{!U||U===1/0||(window.clearTimeout(D.current),O.current=new Date().getTime(),D.current=window.setTimeout(J,U))},[J]);d.useEffect(()=>{const U=S.viewport;if(U){const ne=()=>{G(A.current),f==null||f()},M=()=>{const ee=new Date().getTime()-O.current;A.current=A.current-ee,window.clearTimeout(D.current),u==null||u()};return U.addEventListener(ew,M),U.addEventListener(tw,ne),()=>{U.removeEventListener(ew,M),U.removeEventListener(tw,ne)}}},[S.viewport,P,u,f,G]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&G(P)},[i,P,S.isClosePausedRef,G]),d.useEffect(()=>(B(),()=>V()),[B,V]);const se=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,se&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},se),d.createElement(Vee,{scope:n,onClose:J},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||J(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Ae.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(C.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!C.current)return;const ne=U.clientX-C.current.x,M=U.clientY-C.current.y,ee=!!R.current,H=["left","right"].includes(S.swipeDirection),X=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,W=H?X(0,ne):0,le=H?0:X(0,M),pe=U.pointerType==="touch"?10:2,$e={x:W,y:le},Ve={originalEvent:U,delta:$e};ee?(R.current=$e,Th(jee,p,Ve,{discrete:!1})):s$($e,S.swipeDirection,pe)?(R.current=$e,Th(Fee,m,Ve,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(ne)>pe||Math.abs(M)>pe)&&(C.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const ne=R.current,M=U.target;if(M.hasPointerCapture(U.pointerId)&&M.releasePointerCapture(U.pointerId),R.current=null,C.current=null,ne){const ee=U.currentTarget,H={originalEvent:U,delta:ne};s$(ne,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,H,{discrete:!0}):Th(zee,g,H,{discrete:!0}),ee.addEventListener("click",X=>X.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Ae.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Ae.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Ae.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const E=x[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?je.createElement(d.Fragment,null,e.children):je.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,x]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const O=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),O&&D.classList.add(O)):O?D.setAttribute(l,O):D.removeAttribute(l),r){const B=cm.includes(s)?s:null,V=cm.includes(P)?P:B;D.style.colorScheme=V}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),b=d.useCallback(R=>{const P=l$(R);x(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(b),b(R),()=>R.removeListener(b)},[b]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return je.createElement(sM.Provider,{value:C},je.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,S=!1,E=!0)=>{const _=s?s[x]:x,b=S?x+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(x)&&(C+=`d.style.colorScheme = '${x}';`),n==="class"?C+=S||_?`c.add(${b})`:"null":_&&(C+=`d[s](n,${b})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return je.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(je.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-c6LmMFap.js b/py/iopaint/web_app/assets/index-c6LmMFap.js new file mode 100644 index 0000000..991a916 --- /dev/null +++ b/py/iopaint/web_app/assets/index-c6LmMFap.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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. + */var kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ce=K[se];if(0>>1;seo(We,H))Oeo(he,We)?(K[se]=he,K[Oe]=H,se=Oe):(K[se]=We,K[Ue]=H,se=Ue);else if(Oeo(he,H))K[se]=he,K[Oe]=H,se=Oe;else break e}}return Z}function o(K,Z){var H=K.sortIndex-Z.sortIndex;return H!==0?H:K.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,b=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(K){for(var Z=n(f);Z!==null;){if(Z.callback===null)r(f);else if(Z.startTime<=K)r(f),Z.sortIndex=Z.expirationTime,t(u,Z);else break;Z=n(f)}}function R(K){if(S=!1,C(K),!b)if(n(u)!==null)b=!0,N(P);else{var Z=n(f);Z!==null&&ie(R,Z.startTime-K)}}function P(K,Z){b=!1,S&&(S=!1,_(D),D=-1),y=!0;var H=g;try{for(C(Z),p=n(u);p!==null&&(!(p.expirationTime>Z)||K&&!q());){var se=p.callback;if(typeof se=="function"){p.callback=null,g=p.priorityLevel;var ce=se(p.expirationTime<=Z);Z=e.unstable_now(),typeof ce=="function"?p.callback=ce:p===n(u)&&r(u),C(Z)}else r(u);p=n(u)}if(p!==null)var Ve=!0;else{var Ue=n(f);Ue!==null&&ie(R,Ue.startTime-Z),Ve=!1}return Ve}finally{p=null,g=H,y=!1}}var M=!1,A=null,D=-1,U=5,W=-1;function q(){return!(e.unstable_now()-WK||125se?(K.sortIndex=H,t(f,K),n(u)===null&&K===n(f)&&(S?(_(D),D=-1):S=!0,ie(R,H-se))):(K.sortIndex=ce,t(u,K),b||y||(b=!0,N(P))),K},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(K){var Z=g;return function(){var H=g;g=Z;try{return K.apply(this,arguments)}finally{g=H}}}})(P$);T$.exports=P$;var XD=T$.exports;/** + * @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. + */var A$=d,yr=XD;function ue(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function JD(e,t,n,r){if(t===null||typeof t>"u"||QD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(e,2,!1,e,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(e){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(e){return e[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(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Y0(t);case 8:return t===cw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ue(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ue(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ue(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ue(62))}}function ty(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ue(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ue(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ue(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ue(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(U=A,A=null):U=A.sibling;var W=g(_,A,C[D],R);if(W===null){A===null&&(A=U);break}e&&A&&W.alternate===null&&t(_,A),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W,A=U}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(U=A,A=null):U=A.sibling;var q=g(_,A,W.value,R);if(q===null){A===null&&(A=U);break}e&&A&&q.alternate===null&&t(_,A),x=i(q,x,D),M===null?P=q:M.sibling=q,M=q,A=U}if(W.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!W.done;D++,W=C.next())W=p(_,W.value,R),W!==null&&(x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return Dt&&ta(_,D),P}for(A=r(_,A);!W.done;D++,W=C.next())W=y(A,_,D,W.value,R),W!==null&&(e&&W.alternate!==null&&A.delete(W.key===null?D:W.key),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return e&&A.forEach(function(X){return t(_,X)}),Dt&&ta(_,D),P}function E(_,x,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,M=x;M!==null;){if(M.key===P){if(P=C.type,P===ml){if(M.tag===7){n(_,M.sibling),x=o(M,C.props.children),x.return=_,_=x;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===M.type){n(_,M.sibling),x=o(M,C.props),x.ref=iu(_,M,C),x.return=_,_=x;break e}n(_,M);break}else t(_,M);M=M.sibling}C.type===ml?(x=$a(C.props.children,_.mode,R,C.key),x.return=_,_=x):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,x,C),R.return=_,_=R)}return s(_);case pl:e:{for(M=C.key;x!==null;){if(x.key===M)if(x.tag===4&&x.stateNode.containerInfo===C.containerInfo&&x.stateNode.implementation===C.implementation){n(_,x.sibling),x=o(x,C.children||[]),x.return=_,_=x;break e}else{n(_,x);break}else t(_,x);x=x.sibling}x=c0(C,_.mode,R),x.return=_,_=x}return s(_);case Ji:return M=C._init,E(_,x,M(C._payload),R)}if(yu(C))return b(_,x,C,R);if(eu(C))return S(_,x,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,x!==null&&x.tag===6?(n(_,x.sibling),x=o(x,C),x.return=_,_=x):(n(_,x),x=l0(C,_.mode,R),x.return=_,_=x),s(_)):n(_,x)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ue(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ue(407));n=n()}else{if(n=t(),dn===null)throw Error(ue(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ue(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ue(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var b=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(b!==null){var S=b.memoizedProps,E=b.memoizedState,_=t.stateNode,x=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ue(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return b=LE,LE=!1,b}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ty(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Py(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(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||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ue(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ue(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ue(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ue(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ue(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ue(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ue(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ue(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ue(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Te(this,ga,void 0);Te(this,rs,void 0);Te(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,rs)||this.setEventListener(z(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=z(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ga)=="boolean"?z(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Te(this,Ll,!0);Te(this,os,void 0);Te(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,os)||this.setEventListener(z(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=z(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){z(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},b=()=>new Promise(E=>{var _;o=x=>{const C=r||!p();return C&&E(x),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var M;if(r)return;const x=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=x===!0||typeof x=="number"&&n{if(p())return b()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():b().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Te(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){z(this,va)&&(clearTimeout(z(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Te(this,Bl);Te(this,ao);Te(this,jl,void 0);Te(this,zl,void 0);Te(this,Nr,void 0);Te(this,is,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,vd,void 0);Te(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=z(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,is);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,jl))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,ya)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,is))return(f=z(this,Dr))==null||f.continueRetry(),z(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=z(this,cn).find(b=>b.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var b,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(b=z(this,Nr).config).onError)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var b,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(b=z(this,Nr).config).onSuccess)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,b)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:b})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,z(this,Dr).promise),z(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...z(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&z(this,zl)?{...z(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Te(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Mo).has(t.queryHash)||(z(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Mo).get(t)}getAll(){return[...z(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Te(this,No);Te(this,Oo,void 0);Te(this,yd,void 0);Te(this,dr,void 0);Te(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,Oo).includes(t)||(z(this,Oo).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,z(this,Oo).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,U)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:U})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const U=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));U!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:U,variables:t})}const D=await n();return await((f=(u=z(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(b=this.options).onSettled)==null?void 0:S.call(b,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=z(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(x=this.options).onError)==null?void 0:C.call(x,D,t,this.state.context)),await((P=(R=z(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{z(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Te(this,Ir,void 0);Te(this,wd,void 0);Te(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>XE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(z(this,wa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),z(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var b,S,E,_,x;const o=t.options,i=(E=(S=(b=t.fetchOptions)==null?void 0:b.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((x=t.state.data)==null?void 0:x.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const M={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(M);const A=await p(M),{maxPages:D}=t.options,U=P?tL:eL;return{pages:U(C.pages,A,D),pageParams:U(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},M=R(o,P);y=await g(P,M,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Te(this,nn,void 0);Te(this,ss,void 0);Te(this,as,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ls,void 0);Te(this,Hl,void 0);Te(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,z(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,z(this,ls)===0&&((e=z(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=z(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,ss).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,ss)}getDefaultOptions(){return z(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){z(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Te(this,Ea);Te(this,bd);Te(this,Sd);Te(this,_d);Te(this,Ed);Te(this,Cd);Te(this,$d);Te(this,Rd);Te(this,um);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Gl,void 0);Te(this,kn,void 0);Te(this,xa,void 0);Te(this,Yl,void 0);Te(this,Do,void 0);Te(this,xd,void 0);Te(this,Xl,void 0);Te(this,Zl,void 0);Te(this,ba,void 0);Te(this,Sa,void 0);Te(this,cs,void 0);Te(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),eC(z(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(z(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,xa),l=z(this,Yl),f=t!==r?t.state:z(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:b}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),U=A&&tC(t,r,n,o);(D||U)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(b="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===z(this,xd))E=z(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&b==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Zl))==null?void 0:M.state.data,z(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(b="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}z(this,Do)&&(p=z(this,Do),E=z(this,Xl),g=Date.now(),b="error");const _=y==="fetching",x=b==="pending",C=b==="error",R=x&&_;return{status:b,fetchStatus:y,isPending:x,isSuccess:b==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!x,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,xa,z(this,Ct).state),ye(this,Yl,this.options),z(this,xa).data!==void 0&&ye(this,Zl,z(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,_a).size)return!0;const u=new Set(l??z(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(f=>{const m=f;return z(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||z(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(z(this,cs))||z(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},z(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){z(this,ba)&&(clearTimeout(z(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){z(this,Sa)&&(clearInterval(z(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:b}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\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$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),b=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),x=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),M=kt("skew"),A=kt("space"),D=kt("translate"),U=()=>["auto","contain","none"],W=()=>["auto","hidden","clip","visible","scroll"],q=()=>["auto",Je,t],X=()=>[Je,t],ae=()=>["",oo,Gi],V=()=>["auto",ha,Je],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],N=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Z=()=>["","0",Je],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],se=()=>[ha,ch],ce=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:se(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:X(),borderWidth:ae(),contrast:se(),grayscale:Z(),hueRotate:ce(),invert:Z(),gap:X(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:q(),margin:q(),opacity:se(),padding:X(),saturate:se(),scale:se(),sepia:Z(),skew:ce(),space:X(),translate:X()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),Je]}],overflow:[{overflow:W()}],"overflow-x":[{"overflow-x":W()}],"overflow-y":[{"overflow-y":W()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:q()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Z()}],shrink:[{shrink:Z()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...N(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:X()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...N(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:N()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...N()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ce()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ce()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":X()}],"scroll-mx":[{"scroll-mx":X()}],"scroll-my":[{"scroll-my":X()}],"scroll-ms":[{"scroll-ms":X()}],"scroll-me":[{"scroll-me":X()}],"scroll-mt":[{"scroll-mt":X()}],"scroll-mr":[{"scroll-mr":X()}],"scroll-mb":[{"scroll-mb":X()}],"scroll-ml":[{"scroll-ml":X()}],"scroll-p":[{"scroll-p":X()}],"scroll-px":[{"scroll-px":X()}],"scroll-py":[{"scroll-py":X()}],"scroll-ps":[{"scroll-ps":X()}],"scroll-pe":[{"scroll-pe":X()}],"scroll-pt":[{"scroll-pt":X()}],"scroll-pr":[{"scroll-pr":X()}],"scroll-pb":[{"scroll-pb":X()}],"scroll-pl":[{"scroll-pl":X()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return oe.isArray(e)&&!e.some(qy)}const oj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!oe.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function f(b){if(b===null)return"";if(oe.isDate(b))return b.toISOString();if(!u&&oe.isBlob(b))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(b)||oe.isTypedArray(b)?u&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function m(b,S,E){let _=b;if(b&&!E&&typeof b=="object"){if(oe.endsWith(S,"{}"))S=r?S:S.slice(0,-2),b=JSON.stringify(b);else if(oe.isArray(b)&&rj(b)||(oe.isFileList(b)||oe.endsWith(S,"[]"))&&(_=oe.toArray(b)))return S=iT(S),_.forEach(function(C,R){!(oe.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(b)?!0:(t.append(pC(E,S,i),f(b)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(b,S){if(!oe.isUndefined(b)){if(p.indexOf(b)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(b),oe.forEach(b,function(_,x){(!(oe.isUndefined(_)||_===null)&&o.call(t,_,oe.isString(x)?x.trim():x,S,g))===!0&&y(_,S?S.concat(x):[x])}),p.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:oe.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=oe.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>oe.forEach(l,(f,m)=>i(f,m,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=oe.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(oe.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&oe.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),oe.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const b=Tj(g);if(b&&zo.protocols.indexOf(b)===-1){r(new ut("Unsupported protocol "+b+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};oe.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>oe.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return oe.isPlainObject(f)&&oe.isPlainObject(m)?oe.merge.call({caseless:p},f,m):oe.isPlainObject(m)?oe.merge({},m):oe.isArray(m)?m.slice():m}function o(f,m,p){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!oe.isUndefined(m))return r(void 0,m)}function s(f,m){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);oe.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],b=>{delete i[b]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const b=[xC.bind(this),void 0];for(b.unshift.apply(b,l),b.push.apply(b,f),g=b.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return oe.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return oe.extend(n,Gh.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Be(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(b=>{let[S,E]=b;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const x=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return x},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let b;const S=()=>{var E;if(!f)return;s=!1,l.forEach(x=>x(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)return i.deserialize(x)}).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return b=i.merge(x,(C=r())!=null?C:y),n(b,!0),p()}).then(()=>{_==null||_(b,void 0),s=!0,u.forEach(x=>x(b))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),b||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const b=()=>{var S,E;if(!f)return;s=!1,l.forEach(x=>{var C;return x((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return y=i.merge(x,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(x=>x(y))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>b(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||b(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @license React + * use-sync-external-store-shim.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. + */var lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var b=s.value;if(o(b,y))return p=b}return p=y}if(b=p,Zz(m,y))return b;var S=r(y);return o!==void 0&&o(b,S)?b:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=Fe,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:b,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],x=[];if(E===!0?(x=m,_=b):(x=p,_=S),x.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,x];e(M=>{M.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const M=y[y.length-2];R=await Nu(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];R=await Nu(M.currentSrc,r.name,r.type)}const P=Wh(i,s,[x],_);if(E){const M=await cC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=M;D&&t().setSeed(parseInt(D,10));const U=new Image;await Vh(U,A);const W=[...y,U];t().setImageSize(U.width,U.height),t().updateEditorState({renders:W,lineGroups:C,lastLineGroup:x,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(M){ul({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(b=>{b.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const b=[...i,y],S=[...s,[]];t().updateEditorState({renders:b,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function de(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...b}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>b,Object.values(b));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,b=d.useContext(y);if(b)return b;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,b]=d.useState({}),S=Be(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),x=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=x,M=bB(D=>{const U=D.target,W=[...m.branches].some(q=>q.contains(U));!P||W||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const U=D.target;[...m.branches].some(q=>q.contains(U))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>b({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Pe.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,A.onFocusCapture),onBlurCapture:de(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,M.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Pe.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},b=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),b=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",x=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[b]+i.reference[y]-g[y]-i.floating[b],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=M?M[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[C]||i.floating[b]);const D=R/2-P/2,U=A/2-S[b]/2-1,W=Ts(p[_],U),q=Ts(p[x],U),X=W,ae=A-S[b]-q,V=A/2-S[b]/2+D,F=c1(X,V,ae),N=!u.arrow&&Cc(o)!=null&&V!=F&&i.reference[b]/2-(VX<=0)){var U,W;const X=(((U=i.flip)==null?void 0:U.index)||0)+1,ae=P[X];if(ae)return{data:{index:X,overflows:D},reset:{placement:ae}};let V=(W=D.filter(F=>F.overflows[0]<=0).sort((F,N)=>F.overflows[1]-N.overflows[1])[0])==null?void 0:W.placement;if(!V)switch(y){case"bestFit":{var q;const F=(q=D.map(N=>[N.placement,N.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((N,ie)=>N[1]-ie[1])[0])==null?void 0:q[0];F&&(V=F);break}case"initialPlacement":V=l;break}if(o!==V)return{reset:{placement:V}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof b=="number"&&(y=l==="end"?b*-1:b),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:x}=E;return{x:_,y:x}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],b=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",x=y+m[E],C=y-m[_];y=c1(x,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",x=b+m[E],C=b-m[_];b=c1(x,b,C)}const S=l.fn({...t,[g]:y,[p]:b});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],b=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,x;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),M=i.reference[p]+i.reference[C]+(R?0:((x=s.offset)==null?void 0:x[p])||0)-(R?E.crossAxis:0);bM&&(b=M)}return{[g]:y,[p]:b}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let b,S;f==="top"||f==="bottom"?(b=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,b=m==="end"?"top":"bottom");const E=y-u[b],_=g-u[S],x=!t.middlewareData.shift;let C=E,R=_;if(p){const M=g-u.left-u.right;R=m||x?Ts(_,M):M}else{const M=y-u.top-u.bottom;C=m||x?Ts(E,M):M}if(x&&!m){const M=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),U=hr(u.bottom,0);p?R=g-2*(M!==0||A!==0?M+A:hr(u.left,u.right)):C=y-2*(D!==0||U!==0?D+U:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let b=g.frameElement;for(;b&&r&&y!==g;){const S=Nl(b),E=b.getBoundingClientRect(),_=Xr(b),x=E.left+(b.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(b.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=x,f+=C,b=vr(b).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),b=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),x={rootMargin:-y+"px "+-b+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const M=P[0].intersectionRatio;if(M!==u){if(!C)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...x,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,x)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[x]=_;x&&x.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let b,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,b=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(b)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!jp(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[b,S]=d.useState(null),[E,_]=d.useState(null),x=d.useCallback(N=>{N!=M.current&&(M.current=N,S(N))},[S]),C=d.useCallback(N=>{N!==A.current&&(A.current=N,_(N))},[_]),R=i||b,P=s||E,M=d.useRef(null),A=d.useRef(null),D=d.useRef(m),U=VC(u),W=VC(o),q=d.useCallback(()=>{if(!M.current||!A.current)return;const N={placement:t,strategy:n,middleware:g};W.current&&(N.platform=W.current),aU(M.current,A.current,N).then(ie=>{const K={...ie,isPositioned:!0};X.current&&!jp(D.current,K)&&(D.current=K,Is.flushSync(()=>{p(K)}))})},[g,t,n,W]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(N=>({...N,isPositioned:!1})))},[f]);const X=d.useRef(!1);Zh(()=>(X.current=!0,()=>{X.current=!1}),[]),Zh(()=>{if(R&&(M.current=R),P&&(A.current=P),R&&P){if(U.current)return U.current(R,P,q);q()}},[R,P,q,U]);const ae=d.useMemo(()=>({reference:M,floating:A,setReference:x,setFloating:C}),[x,C]),V=d.useMemo(()=>({reference:R,floating:P}),[R,P]),F=d.useMemo(()=>{const N={position:n,left:0,top:0};if(!V.floating)return N;const ie=UC(V.floating,m.x),K=UC(V.floating,m.y);return l?{...N,transform:"translate("+ie+"px, "+K+"px)",...zT(V.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,V.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:q,refs:ae,elements:V,floatingStyles:F}),[m,q,ae,V,F])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Be(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Pe.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:b=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:x=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,D=VT(WT,m),[U,W]=d.useState(null),q=Be(t,Kt=>W(Kt)),[X,ae]=d.useState(null),V=yx(X),F=(n=V==null?void 0:V.width)!==null&&n!==void 0?n:0,N=(r=V==null?void 0:V.height)!==null&&r!==void 0?r:0,ie=p+(y!=="center"?"-"+y:""),K=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},Z=Array.isArray(_)?_:[_],H=Z.length>0,se={padding:K,boundary:Z.filter(gU),altBoundary:H},{refs:ce,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Oe}=cU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+N,alignmentAxis:b}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...se}),E&&IB({...se}),UB({...se,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Q}=Er.reference,J=Kt.floating.style;J.setProperty("--radix-popper-available-width",`${gt}px`),J.setProperty("--radix-popper-available-height",`${Vs}px`),J.setProperty("--radix-popper-anchor-width",`${L}px`),J.setProperty("--radix-popper-anchor-height",`${Q}px`)}}),X&&lU({element:X,padding:S}),vU({arrowWidth:F,arrowHeight:N}),R&&LB({strategy:"referenceHidden",...se})]}),[he,xe]=HT(Ue),$e=Ft(M);An(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Oe.arrow)===null||o===void 0?void 0:o.x,Me=(i=Oe.arrow)===null||i===void 0?void 0:i.y,je=((s=Oe.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{U&&ct(window.getComputedStyle(U).zIndex)},[U]),d.createElement("div",{ref:ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Oe.transformOrigin)===null||l===void 0?void 0:l.x,(u=Oe.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:he,onArrowChange:ae,arrowX:Ae,arrowY:Me,shouldHideArrow:je},d.createElement(Pe.div,Y({"data-side":he,"data-align":xe},A,{ref:q,style:{...A.style,animation:We?void 0:"none",opacity:(f=Oe.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[b,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,x=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return b==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):b==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):b==="right"?(C=`${-y}px`,R=p?E:`${x}px`):b==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${x}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Pe.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),b=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,x]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,x(!0)},[x]),P=d.useCallback(()=>{window.clearTimeout(y.current),x(!1)},[x]),M=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,x(!0)},S)},[S,x]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?M():R()},[u.isOpenDelayed,M,R]),onTriggerLeave:d.useCallback(()=>{b?P():window.clearTimeout(y.current)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Be(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:de(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:de(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:de(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Be(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((b,S)=>{const E=b.currentTarget,_={x:b.clientX,y:b.clientY},x=NU(_,E.getBoundingClientRect()),C=DU(_,x),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const b=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",b),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",b),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const b=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},x=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);x?g():C&&(g(),f())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.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)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={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"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("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"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("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"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("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"}]]),sV=Jt("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"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Be(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let x=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(M){if(document.activeElement===document.body)for(const D of M)D.removedNodes.length>0&&Qi(l)};var S=x,E=C,_=R;document.addEventListener("focusin",x),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const b=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const x=S.currentTarget,[C,R]=uV(x);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===x&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:b}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),b=y[0],S=y[1],E=y[2],_=S-E-i*b;(b||_)&&iP(e,l)&&(p+=_,g+=b),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),x=n.current,C="deltaX"in S?S.deltaX:x[0]-_[0],R="deltaY"in S?S.deltaY:x[1]-_[1],P,M=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&M.type==="range")return!1;var D=JC(A,M);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,M)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var U=r.current||P;return VV(U,E,S,U==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),x=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(x&&x.should){E.cancelable&&E.preventDefault();return}if(!x){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,x){var C={name:S,delta:E,target:_,should:x};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,b=e.inert;return d.createElement(d.Fragment,null,b?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),b=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&b&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),b||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Be(t,o.triggerRef);return d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:de(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Pe.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Be(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Be(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,b=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!b&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,b=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var M;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(M=R.target)!=null&&M.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,U=P0(A,p==null?void 0:p.combinationKey);if(_W(R,U,p==null?void 0:p.ignoreModifiers)||(D=U.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,U,p==null?void 0:p.preventDefault),!xW(R,U,p==null?void 0:p.enabled)){n2(R);return}m.current(R,U),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},x=o.current||(s==null?void 0:s.document)||document;return x.addEventListener("keyup",_),x.addEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){x.removeEventListener("keyup",_),x.removeEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Be(t,o.triggerRef),l=d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:de(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Be(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.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)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,b=1,S=2,E=1,_=2,x=4,C=8,R=16,P=32,M=64,A=128,D=256,U=512,W=30,q="...",X=800,ae=16,V=1,F=2,N=3,ie=1/0,K=9007199254740991,Z=17976931348623157e292,H=NaN,se=4294967295,ce=se-1,Ve=se>>>1,Ue=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",U],["partial",P],["partialRight",M],["rearg",D]],We="[object Arguments]",Oe="[object Array]",he="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Me="[object Error]",je="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Q="[object RegExp]",J="[object Set]",we="[object String]",me="[object Symbol]",fe="[object Undefined]",Re="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,G=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(G.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Oe]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[$e]=Rt[Me]=Rt[je]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Q]=Rt[J]=Rt[we]=Rt[Re]=!1;var Et={};Et[We]=Et[Oe]=Et[ht]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Q]=Et[J]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Me]=Et[je]=Et[Re]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var j=Hs&&Hs.require&&Hs.require("util").types;return j||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(j,te,ee){switch(ee.length){case 0:return j.call(te);case 1:return j.call(te,ee[0]);case 2:return j.call(te,ee[0],ee[1]);case 3:return j.call(te,ee[0],ee[1],ee[2])}return j.apply(te,ee)}function XM(j,te,ee,Se){for(var Ke=-1,pt=j==null?0:j.length;++Ke-1}function Ng(j,te,ee){for(var Se=-1,Ke=j==null?0:j.length;++Se-1;);return ee}function Gb(j,te){for(var ee=j.length;ee--&&Va(te,j[ee],0)>-1;);return ee}function oO(j,te){for(var ee=j.length,Se=0;ee--;)j[ee]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(j){return"\\"+HM[j]}function lO(j,te){return j==null?n:j[te]}function Wa(j){return FM.test(j)}function cO(j){return jM.test(j)}function uO(j){for(var te,ee=[];!(te=j.next()).done;)ee.push(te.value);return ee}function Ug(j){var te=-1,ee=Array(j.size);return j.forEach(function(Se,Ke){ee[++te]=[Ke,Se]}),ee}function Yb(j,te){return function(ee){return j(te(ee))}}function ji(j,te){for(var ee=-1,Se=j.length,Ke=0,pt=[];++ee-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var O,I=c&p,B=c&g,ne=c&y;if(h&&(O=$?h(a,w,$,T):h(a)),O!==n)return O;if(!It(a))return a;var re=Ge(a);if(re){if(O=tN(a),!I)return Wn(a,O)}else{var le=Cn(a),ge=le==je||le==Mt;if(Hi(a))return PS(a,I);if(le==gt||le==We||ge&&!$){if(O=B||ge?{}:XS(a),!I)return B?W6(a,h6(O,a)):V6(a,sS(O,a))}else{if(!Et[le])return $?a:{};O=nN(a,le,I)}}T||(T=new eo);var ke=T.get(a);if(ke)return ke;T.set(a,O),E_(a)?a.forEach(function(Le){O.add(Pr(Le,c,h,Le,a,T))}):S_(a)&&a.forEach(function(Le,nt){O.set(nt,Pr(Le,c,h,nt,a,T))});var Ie=ne?B?pv:hv:B?Kn:ln,Qe=re?n:Ie(a);return Rr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Wc(O,nt,Pr(Le,c,h,nt,a,T))}),O}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],O=a[$];if(O===n&&!($ in a)||!T(O))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,O=!0,I=a.length,B=[],ne=c.length;if(!I)return B;h&&(c=Ot(c,ir(h))),w?(T=Ng,O=!1):c.length>=o&&(T=Fc,O=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&re.length>=120)?new Ys(O&&re):n}re=a[0];var le=-1,ge=I[0];e:for(;++le<$&&ne.length-1;)I!==a&&gf.call(I,B,1),gf.call(a,B,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),O=ee(T);T--;)O[w?T:++$]=a,a+=h;return O}function ov(a,c){var h="";if(!a||c<1||c>K)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,O=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=ee($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,O=a[T];O!==null&&!ar(O)&&(h?O<=c:O=o){var ne=c?null:Y6(a);if(ne)return lf(ne);O=!1,$=Fc,B=new Ys}else B=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),O=c!==n,I=c===null,B=c===c,ne=ar(c);if(!I&&!ne&&!T&&a>c||T&&O&&B&&!I&&!ne||w&&O&&B||!h&&B||!$)return 1;if(!w&&!T&&!ne&&a=I)return B;var ne=h[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,O=h.length,I=-1,B=c.length,ne=tn(T-O,0),re=ee(B+ne),le=!w;++I1?h[$-1]:n,O=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,O&&Nn(h[0],h[1],O)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,O=St(h);(c?T--:++T<$)&&w(O[T],T,O)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),O=w(c),I=O.length;I--;){var B=O[a?I:++$];if(h(T[B],B,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var O=this&&this!==fn&&this instanceof T?$:a;return O.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,O=ee(T),I=T,B=Ja($);I--;)O[I]=arguments[I];var ne=T<3&&O[0]!==B&&O[T-1]!==B?[]:ji(O,B);if(T-=ne.length,T-1?$[T?c[O]:O]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!O&&Nf(T)=="wrapper")var O=new Tr([],!0)}for(w=O?w:h;++w1&&at.reverse(),re&&BI))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var le=-1,ge=!0,ke=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++le1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??K,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=X)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,De(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ie)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,De(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,De(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?ee(a.length):[];return Bi(a,function(O){T[++w]=$?or(c,O,h):Kc(O,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,De(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(De(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==J?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,O,I,B,ne=0,re=!1,le=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(re=!!h.leading,le="maxWait"in h,T=le?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function ke(Yt){var no=w,ci=$;return w=$=n,ne=Yt,O=a.apply(ci,no),O}function Ie(Yt){return ne=Yt,I=qc(nt,c),re?ke(Yt):O}function Qe(Yt){var no=Yt-B,ci=Yt-ne,F_=c-no;return le?En(F_,T-ci):F_}function Le(Yt){var no=Yt-B,ci=Yt-ne;return B===n||no>=c||no<0||le&&ci>=T}function nt(){var Yt=jf();if(Le(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?ke(Yt):(w=$=n,O)}function lr(){I!==n&&TS(I),ne=0,w=B=$=I=n}function Dn(){return I===n?O:at(jf())}function cr(){var Yt=jf(),no=Le(Yt);if(w=arguments,$=this,B=Yt,no){if(I===n)return Ie(B);if(le)return TS(I),I=qc(nt,c),ke(B)}return I===n&&(I=qc(nt,c)),O}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,U)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var O=a.apply(this,w);return h.cache=T.set($,O)||T,O};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(De())):Ot(hn(c,1),ir(De()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=ee.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==J)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Me||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==je||c==Mt||c==he||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-K&&a<=K}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==Re}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==J?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Z}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,se):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return H;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?H:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(De(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=De(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=De(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(O,I,B){return c(h,O,I,B)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(G,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),O=Bg($,T),I,B,ne=0,re=c.interpolate||nf,le="__p += '",ge=Vg((c.escape||nf).source+"|"+re.source+"|"+(re===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),ke="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Le,nt,at,lr,Dn,cr){return at||(at=lr),le+=a.slice(ne,cr).replace(yM,aO),nt&&(I=!0,le+=`' + +__e(`+nt+`) + +'`),Dn&&(B=!0,le+=`'; +`+Dn+`; +__p += '`),at&&(le+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),le+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)le=`with (obj) { +`+le+` +} +`;else if(cM.test(Ie))throw new Ke(l);le=(B?le.replace(bg,""):le).replace(Sg,"$1").replace(Jd,"$1;"),le="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+le+`return __p +}`;var Qe=I_(function(){return pt(T,ke+"return "+le).apply(n,O)});if(Qe.source=le,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),O=Gb(w,$)+1;return Wi(w,T,O).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=W,w=q;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var O=Jr(a);T=O.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var B=O?Wi(O,0,I).join(""):a.slice(0,I);if($===n)return B+w;if(O&&(I+=B.length-I),Rv($)){if(a.slice(I).search($)){var ne,re=B;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var le=ne.index;B=B.slice(0,le===n?I:le)}}else if(a.indexOf(sr($),I)!=I){var ge=B.lastIndexOf($);ge>-1&&(B=B.slice(0,ge))}return B+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=De();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var h=se,w=En(a,se);c=De(c),a-=se;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(se)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var O=this.__wrapped__,I=w?[1]:arguments,B=O instanceof ot,ne=I[0],re=B||Ge(O),le=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};re&&h&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var ge=this.__chain__,ke=!!this.__actions__.length,Ie=T&&!ge,Qe=B&&!ke;if(!T&&re){O=Qe?O:new ot(this);var Le=a.apply(O,I);return Le.__actions__.push({func:Lf,args:[le],thisArg:n}),new Tr(Le,ge)}return Ie&&Qe?a.apply(this,I):(Le=this.thru(le),Ie?w?Le.value()[0]:Le.value():Le)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(O){return c.apply(Ge(O)?O:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),b=i.get(p);(b===void 0||b>g&&(b/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let b=i+g;by);b+=1){const S=RH(e,i,b,u,n,f,m);if(S===void 0)break;p.set(b,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:b,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:b})=>b),o,n,r);m.push(g.map(({photo:b,index:S},E)=>({photo:b,layout:{height:y,width:y*Vr(b),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},b=E=>{const{src:_,alt:x,srcSet:C,sizes:R,style:P,...M}=y;return d.createElement("img",{alt:x,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},S=(({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M})=>({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:b,wrapperStyle:S}))!=null?n:b())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,b=g[s+1];(!b||b.weight>y&&(b.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:b})).slice(e[f],e[f+1]),p=o.reduce((y,b,S)=>y+(r[f]-r[S])*b,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:b},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:b,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:b}}const f=(e.reduce((y,b)=>y+n/Vr(b),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:b})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:b,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((b,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:b})=>g+y/b*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,b=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,b))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),b=_+m,S){let D=0;for(;D=W;V-=1){let F=V-1,N=n[e.charAt(F)];if(S&&(E[F]=+!!N),X[V]=(X[V+1]<<1|1)&N,A&&(X[V]|=(x[V+1]|x[V])<<1|1|x[V+1]),X[V]&P&&(C=xh(t,{errors:A,currentLocation:F,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,b=F,b<=g)break;W=Math.max(1,2*g-b)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;x=X}const M={isMatch:b>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,b=p-y;for(;g{const{isMatch:_,score:x,indices:C}=MK(t,b,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=x,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:b,children:S}=y,E=Fe.useRef(null),_=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:b,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=Fe.forwardRef((y,b)=>{const{scope:S,children:E}=y,_=i(l,S),x=Be(b,_.collectionRef);return Fe.createElement(Zo,{ref:x},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=Fe.forwardRef((y,b)=>{const{scope:S,children:E,..._}=y,x=Fe.useRef(null),C=Be(b,x),R=i(f,S);return Fe.useEffect(()=>(R.itemMap.set(x,{ref:x,..._}),()=>void R.itemMap.delete(x))),Fe.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const b=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const E=b.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Be(t,p),y=Tc(i),[b=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),x=Ft(f),C=ZP(n),R=d.useRef(!1),[P,M]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,x),()=>A.removeEventListener(M0,x)},[x]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:b,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>M(A=>A-1),[])},d.createElement(Pe.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{R.current=!0}),onFocus:de(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const U=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const W=C().filter(F=>F.focusable),q=W.find(F=>F.active),X=W.find(F=>F.id===b),V=[q,X,...W].filter(Boolean).map(F=>F.ref.current);qP(V)}}R.current=!1}),onBlur:de(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Pe.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:de(e.onMouseDown,b=>{r?f.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const S=uG(b,f.orientation,f.dir);if(S!==void 0){b.preventDefault();let _=p().filter(x=>x.focusable).map(x=>x.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const x=_.indexOf(b.currentTarget);_=f.loop?dG(_,x+1):_.slice(x+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Pe.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:de(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:de(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:de(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Pe.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,b=Bx(t),[S,E]=d.useState(null),[_,x]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,U]=Zr({prop:s,defaultProp:l,onChange:u}),W=d.useRef(null),q=S?!!S.closest("form"):!0,[X,ae]=d.useState(new Set),V=Array.from(X).map(F=>F.props.value).join(";");return d.createElement(jd,b,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:x,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:U,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:W,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(F=>{ae(N=>new Set(N).add(F))},[]),onNativeOptionRemove:d.useCallback(F=>{ae(N=>{const ie=new Set(N);return ie.delete(F),ie})},[])},n)),q?d.createElement(f5,{key:V,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:F=>U(F.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(X)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(b=>{const S=f().filter(x=>!x.disabled),E=S.find(x=>x.value===s.value),_=p5(S,b,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:de(o.onClick,b=>{b.currentTarget.focus()}),onPointerDown:de(o.onPointerDown,b=>{const S=b.target;S.hasPointerCapture(b.pointerId)&&S.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)},b.preventDefault())}),onKeyDown:de(o.onKeyDown,b=>{const S=m.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&p(b.key),!(S&&b.key===" ")&&SG.includes(b.key)&&(y(),b.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Be(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Pe.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E,..._}=e,x=Fa(dc,n),[C,R]=d.useState(null),[P,M]=d.useState(null),A=Be(t,he=>R(he)),[D,U]=d.useState(null),[W,q]=d.useState(null),X=og(n),[ae,V]=d.useState(!1),F=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const N=d.useCallback(he=>{const[xe,...$e]=X().map(je=>je.ref.current),[Ae]=$e.slice(-1),Me=document.activeElement;for(const je of he)if(je===Me||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Me))return},[X,P]),ie=d.useCallback(()=>N([D,C]),[N,D,C]);d.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Z}=x;d.useEffect(()=>{if(C){let he={x:0,y:0};const xe=Ae=>{var Me,je,Mt,ct;he={x:Math.abs(Math.round(Ae.pageX)-((Me=(je=Z.current)===null||je===void 0?void 0:je.x)!==null&&Me!==void 0?Me:0)),y:Math.abs(Math.round(Ae.pageY)-((Mt=(ct=Z.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},$e=Ae=>{he.x<=10&&he.y<=10?Ae.preventDefault():C.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Z.current=null};return Z.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[C,K,Z]),d.useEffect(()=>{const he=()=>K(!1);return window.addEventListener("blur",he),window.addEventListener("resize",he),()=>{window.removeEventListener("blur",he),window.removeEventListener("resize",he)}},[K]);const[H,se]=h5(he=>{const xe=X().filter(Me=>!Me.disabled),$e=xe.find(Me=>Me.ref.current===document.activeElement),Ae=p5(xe,he,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ce=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&(U(he),Ae&&(F.current=!0))},[x.value]),Ve=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ue=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&q(he)},[x.value]),We=r==="popper"?p2:LG,Oe=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:M,itemRefCallback:ce,selectedItem:D,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:W,position:r,isPositioned:ae,searchRef:H},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:x.open,onMountAutoFocus:he=>{he.preventDefault()},onUnmountAutoFocus:de(o,he=>{var xe;(xe=x.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),he.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:he=>he.preventDefault(),onDismiss:()=>x.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:he=>he.preventDefault()},_,Oe,{onPlaced:()=>V(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:de(_.onKeyDown,he=>{const xe=he.ctrlKey||he.altKey||he.metaKey;if(he.key==="Tab"&&he.preventDefault(),!xe&&he.key.length===1&&se(he.key),["ArrowUp","ArrowDown","Home","End"].includes(he.key)){let Ae=X().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(he.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(he.key)){const Me=he.target,je=Ae.indexOf(Me);Ae=Ae.slice(je+1)}setTimeout(()=>N(Ae)),he.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Be(t,A=>m(A)),g=og(n),y=d.useRef(!1),b=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:x}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),U=i.valueNode.getBoundingClientRect(),W=_.getBoundingClientRect();if(i.dir!=="rtl"){const Me=W.left-D.left,je=U.left-Me,Mt=A.left-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Me=D.right-W.right,je=window.innerWidth-U.right-Me,Mt=window.innerWidth-A.right-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const q=g(),X=window.innerHeight-hi*2,ae=S.scrollHeight,V=window.getComputedStyle(f),F=parseInt(V.borderTopWidth,10),N=parseInt(V.paddingTop,10),ie=parseInt(V.borderBottomWidth,10),K=parseInt(V.paddingBottom,10),Z=F+N+ae+K+ie,H=Math.min(E.offsetHeight*5,Z),se=window.getComputedStyle(S),ce=parseInt(se.paddingTop,10),Ve=parseInt(se.paddingBottom,10),Ue=A.top+A.height/2-hi,We=X-Ue,Oe=E.offsetHeight/2,he=E.offsetTop+Oe,xe=F+N+he,$e=Z-xe;if(xe<=Ue){const Me=E===q[q.length-1].ref.current;l.style.bottom="0px";const je=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Oe+(Me?Ve:0)+je+ie),ct=xe+Mt;l.style.height=ct+"px"}else{const Me=E===q[0].ref.current;l.style.top="0px";const Mt=Math.max(Ue,F+S.offsetTop+(Me?ce:0)+Oe)+$e;l.style.height=Mt+"px",S.scrollTop=xe-Ue+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=H+"px",l.style.maxHeight=X+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const M=d.useCallback(A=>{A&&b.current===!0&&(C(),x==null||x(),b.current=!1)},[C,x]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Pe.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,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)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Be(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:de(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,b=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(b,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),b=Be(t,_=>{var x;return(x=u.itemRefCallback)===null||x===void 0?void 0:x.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(x=>{var C;return x||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Pe.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:b,onFocus:de(s.onFocus,()=>y(!0)),onBlur:de(s.onBlur,()=>y(!1)),onPointerUp:de(s.onPointerUp,E),onPointerMove:de(s.onPointerMove,_=>{if(o){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:de(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}}),onKeyDown:de(s.onKeyDown,_=>{var x;((x=u.searchRef)===null||x===void 0?void 0:x.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Be(t,_=>p(_),u.onItemTextChange,_=>{var x;return(x=l.itemTextRefCallback)===null||x===void 0?void 0:x.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,b=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(b),()=>E(b)),[S,E,b]),d.createElement(d.Fragment,null,d.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:de(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:de(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:de(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Be(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,b]=d.useState(null),[S,E]=d.useState(null),[_,x]=d.useState(0),[C,R]=d.useState(0),[P,M]=d.useState(!1),[A,D]=d.useState(!1),U=Be(t,q=>u(q)),W=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:W,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:b,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:x,onCornerHeightChange:R},d.createElement(Pe.div,Y({dir:W},s,{ref:U,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Be(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:de(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:de(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[b,S]=d.useState(null),E=Be(t,U=>S(U)),_=d.useRef(null),x=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),M=Ft(u),A=sg(p,10);function D(U){if(_.current){const W=U.clientX-_.current.left,q=U.clientY-_.current.top;f({x:W,y:q})}}return d.useEffect(()=>{const U=W=>{const q=W.target;(b==null?void 0:b.contains(q))&&P(W,R)};return document.addEventListener("wheel",U,{passive:!1}),()=>document.removeEventListener("wheel",U,{passive:!1})},[C,b,R,P]),d.useEffect(M,[r,M]),fc(b,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},d.createElement(Pe.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:de(e.onPointerDown,U=>{U.button===0&&(U.target.setPointerCapture(U.pointerId),_.current=b.getBoundingClientRect(),x.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(U))}),onPointerMove:de(e.onPointerMove,D),onPointerUp:de(e.onPointerUp,U=>{const W=U.target;W.hasPointerCapture(U.pointerId)&&W.releasePointerCapture(U.pointerId),document.body.style.webkitUserSelect=x.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Be(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:de(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),b=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x:b,y:S})}),onPointerUp:de(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(W=>[W.fileManagerState,W.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[b,S]=d.useState(w2),[E,_]=d.useState([]),[x,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let W=R;R>0&&(W=R-1),P(W),t(b,x[W].name)},[R,x]),Zn("right",()=>{let W=R;R{r||p(u)},[r,u]);const M=d.useCallback(W=>{W!==null&&r&&setTimeout(()=>{W.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const q=await Wj(b);_(q)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[b]),d.useEffect(()=>{if(!r)return;(async()=>{try{let q=E;y&&(q=new kc(q,{keys:["name"]}).search(y).map(F=>q[F.refIndex])),q=xH.orderBy(q,i.sortBy,i.sortOrder);const X=q.map(ae=>{const V=n,F=ae.height*(V/ae.width);return{src:`${Ls}/media_thumbnail_file?tab=${b}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(V)}&height=${Math.ceil(F)}`,height:F,width:V,name:ae.name}});C(X)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[E,y,i,n,r]);const A=W=>{f(W.currentTarget.scrollTop)},D=({index:W})=>{o(),P(W),t(b,x[W].name)},U=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${x.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:U()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:W=>{W.preventDefault(),W.stopPropagation();const q=W.target;s({searchText:q.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:b,onValueChange:W=>S(W),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:W=>{switch(W){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(W=>v.jsx(yo,{value:W,children:W},W))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:x,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=Fe.createContext(null),lg=()=>Fe.useContext(U5),OY=e=>{const{children:t,...n}=e;return Fe.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),f=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=Fe.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const b=ve(o._fields,g);b&&(b._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:Fe.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:b,valueAsNumber:S,mount:E,disabled:_}=e._f,x=ve(t,b);if(!E||_)return{};const C=s?s[0]:i,R=X=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(X)?"":X||""),C.reportValidity())},P={},M=Yx(i),A=Yd(i),D=M||A,U=(S||Gx(i))&&Ht(i.value)&&Ht(x)||Hp(i)&&i.value===""||x===""||Array.isArray(x)&&!x.length,W=Y5.bind(null,b,n,P),q=(X,ae,V,F=ui.maxLength,N=ui.minLength)=>{const ie=X?ae:V;P[b]={type:X?F:N,message:ie,ref:i,...W(X?F:N,ie)}};if(o?!Array.isArray(x)||!x.length:l&&(!D&&(U||Fn(x))||Fo(x)&&!x||A&&!X5(s).isValid||M&&!Z5(s).isValid)){const{value:X,message:ae}=np(l)?{value:!!l,message:l}:sl(l);if(X&&(P[b]={type:ui.required,message:ae,ref:C,...W(ui.required,ae)},!n))return R(ae),P}if(!U&&(!Fn(m)||!Fn(p))){let X,ae;const V=sl(p),F=sl(m);if(!Fn(x)&&!isNaN(x)){const N=i.valueAsNumber||x&&+x;Fn(V.value)||(X=N>V.value),Fn(F.value)||(ae=Nnew Date(new Date().toDateString()+" "+H),K=i.type=="time",Z=i.type=="week";Wo(V.value)&&x&&(X=K?ie(x)>ie(V.value):Z?x>V.value:N>new Date(V.value)),Wo(F.value)&&x&&(ae=K?ie(x)+X.value,F=!Fn(ae.value)&&x.length<+ae.value;if((V||F)&&(q(V,X.message,ae.message),!n))return R(P[b].message),P}if(g&&!U&&Wo(x)){const{value:X,message:ae}=sl(g);if(Kp(X)&&!x.match(X)&&(P[b]={type:ui.pattern,message:ae,ref:i,...W(ui.pattern,ae)},!n))return R(ae),P}if(y){if(ms(y)){const X=await y(x,t),ae=$2(X,C);if(ae&&(P[b]={...ae,...W(ui.validate,ae.message)},!n))return R(ae.message),P}else if(sn(y)){let X={};for(const ae in y){if(!Fr(X)&&!n)break;const V=$2(await y[ae](x,t),C,ae);V&&(X={...V,...W(ae,V.message)},R(V.message),n&&(P[b]=X))}if(!Fr(X)&&(P[b]={ref:C,...X},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,b=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Q=>{clearTimeout(m),m=setTimeout(L,Q)},x=async L=>{if(p.isValid||L){const Q=n.resolver?Fr((await U()).errors):await q(o,!0);Q!==r.isValid&&g.state.next({isValid:Q})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Q=[],J,we,me=!0,fe=!0)=>{if(we&&J){if(l.action=!0,fe&&Array.isArray(ve(o,L))){const Re=J(ve(o,L),we.argA,we.argB);me&&wt(o,L,Re)}if(fe&&Array.isArray(ve(r.errors,L))){const Re=J(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,Re),HY(r.errors,L)}if(p.touchedFields&&fe&&Array.isArray(ve(r.touchedFields,L))){const Re=J(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,Re)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:ae(L,Q),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Q)},P=(L,Q)=>{wt(r.errors,L,Q),g.state.next({errors:r.errors})},M=(L,Q,J,we)=>{const me=ve(o,L);if(me){const fe=ve(s,L,Ht(J)?ve(i,L):J);Ht(fe)||we&&we.defaultChecked||Q?wt(s,L,Q?fe:I0(me._f)):N(L,fe),l.mount&&x()}},A=(L,Q,J,we,me)=>{let fe=!1,Re=!1;const ft={name:L};if(!J||we){p.isDirty&&(Re=r.isDirty,r.isDirty=ft.isDirty=ae(),fe=Re!==ft.isDirty);const ht=ma(ve(i,L),Q);Re=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,fe=fe||p.dirtyFields&&Re!==!ht}if(J){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,J),ft.touchedFields=r.touchedFields,fe=fe||p.touchedFields&&ht!==J)}return fe&&me&&g.state.next(ft),fe?ft:{}},D=(L,Q,J,we)=>{const me=ve(r.errors,L),fe=p.isValid&&Fo(Q)&&r.isValid!==Q;if(e.delayError&&J?(f=_(()=>P(L,J)),f(e.delayError)):(clearTimeout(m),f=null,J?wt(r.errors,L,J):pn(r.errors,L)),(J?!ma(me,J):me)||!Fr(we)||fe){const Re={...we,...fe&&Fo(Q)?{isValid:Q}:{},errors:r.errors,name:L};r={...r,...Re},g.state.next(Re)}C(!1)},U=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),W=async L=>{const{errors:Q}=await U(L);if(L)for(const J of L){const we=ve(Q,J);we?wt(r.errors,J,we):pn(r.errors,J)}else r.errors=Q;return Q},q=async(L,Q,J={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:fe,...Re}=me;if(fe){const ft=u.array.has(fe.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Q,ft);if(ht[fe.name]&&(J.valid=!1,Q))break;!Q&&(ve(ht,fe.name)?ft?FY(r.errors,ht,fe.name):wt(r.errors,fe.name,ht[fe.name]):pn(r.errors,fe.name))}Re&&await q(Re,Q,J)}}return J.valid},X=()=>{for(const L of u.unMount){const Q=ve(o,L);Q&&(Q._f.refs?Q._f.refs.every(J=>!N0(J)):!N0(Q._f.ref))&&he(L)}u.unMount=new Set},ae=(L,Q)=>(L&&Q&&wt(s,L,Q),!ma(ce(),i)),V=(L,Q,J)=>K5(L,u,{...l.mount?s:Ht(Q)?i:Wo(L)?{[L]:Q}:Q},J,Q),F=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),N=(L,Q,J={})=>{const we=ve(o,L);let me=Q;if(we){const fe=we._f;fe&&(!fe.disabled&&wt(s,L,e3(Q,fe)),me=Hp(fe.ref)&&Fn(Q)?"":Q,q5(fe.ref)?[...fe.ref.options].forEach(Re=>Re.selected=me.includes(Re.value)):fe.refs?Yd(fe.ref)?fe.refs.length>1?fe.refs.forEach(Re=>(!Re.defaultChecked||!Re.disabled)&&(Re.checked=Array.isArray(me)?!!me.find(ft=>ft===Re.value):me===Re.value)):fe.refs[0]&&(fe.refs[0].checked=!!me):fe.refs.forEach(Re=>Re.checked=Re.value===me):Gx(fe.ref)?fe.ref.value="":(fe.ref.value=me,fe.ref.type||g.values.next({name:L,values:{...s}})))}(J.shouldDirty||J.shouldTouch)&&A(L,me,J.shouldTouch,J.shouldDirty,!0),J.shouldValidate&&se(L)},ie=(L,Q,J)=>{for(const we in Q){const me=Q[we],fe=`${L}.${we}`,Re=ve(o,fe);(u.array.has(L)||!Gp(me)||Re&&!Re._f)&&!$l(me)?ie(fe,me,J):N(fe,me,J)}},K=(L,Q,J={})=>{const we=ve(o,L),me=u.array.has(L),fe=so(Q);wt(s,L,fe),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&J.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:ae(L,fe)})):we&&!we._f&&!Fn(fe)?ie(L,fe,J):N(L,fe,J),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},Z=async L=>{const Q=L.target;let J=Q.name,we=!0;const me=ve(o,J),fe=()=>Q.type?I0(me._f):z5(L),Re=ft=>{we=Number.isNaN(ft)||ft===ve(s,J,ft)};if(me){let ft,ht;const _n=fe(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,J)&&!me._f.deps||WY(Cr,ve(r.touchedFields,J),r.isSubmitted,S,b),Co=S2(J,u,Cr);wt(s,J,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(J,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:J,type:L.type,values:{...s}}),Ni)return p.isValid&&x(),Ba&&g.state.next({name:J,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await U([J]);if(Re(_n),we){const Ws=k2(r.errors,o,J),Ii=k2(Di,o,Ws.name||J);ft=Ii.error,J=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[J],Re(_n),we&&(ft?ht=!1:p.isValid&&(ht=await q(o,!0)));we&&(me._f.deps&&se(me._f.deps),D(J,ht,ft,Vn))}},H=(L,Q)=>{if(ve(r.errors,Q)&&L.focus)return L.focus(),1},se=async(L,Q={})=>{let J,we;const me=ep(L);if(C(!0),n.resolver){const fe=await W(Ht(L)?L:me);J=Fr(fe),we=L?!me.some(Re=>ve(fe,Re)):J}else L?(we=(await Promise.all(me.map(async fe=>{const Re=ve(o,fe);return await q(Re&&Re._f?{[fe]:Re}:Re)}))).every(Boolean),!(!we&&!r.isValid)&&x()):we=J=await q(o);return g.state.next({...!Wo(L)||p.isValid&&J!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:J}:{},errors:r.errors,isValidating:!1}),Q.shouldFocus&&!we&&tp(o,H,L?me:u.mount),we},ce=L=>{const Q={...i,...l.mount?s:{}};return Ht(L)?Q:Wo(L)?ve(Q,L):L.map(J=>ve(Q,J))},Ve=(L,Q)=>({invalid:!!ve((Q||r).errors,L),isDirty:!!ve((Q||r).dirtyFields,L),isTouched:!!ve((Q||r).touchedFields,L),error:ve((Q||r).errors,L)}),Ue=L=>{L&&ep(L).forEach(Q=>pn(r.errors,Q)),g.state.next({errors:L?r.errors:{}})},We=(L,Q,J)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Q,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),J&&J.shouldFocus&&we&&we.focus&&we.focus()},Oe=(L,Q)=>ms(L)?g.values.subscribe({next:J=>L(V(void 0,Q),J)}):V(L,Q,!0),he=(L,Q={})=>{for(const J of L?ep(L):u.mount)u.mount.delete(J),u.array.delete(J),Q.keepValue||(pn(o,J),pn(s,J)),!Q.keepError&&pn(r.errors,J),!Q.keepDirty&&pn(r.dirtyFields,J),!Q.keepTouched&&pn(r.touchedFields,J),!n.shouldUnregister&&!Q.keepDefaultValue&&pn(i,J);g.values.next({values:{...s}}),g.state.next({...r,...Q.keepDirty?{isDirty:ae()}:{}}),!Q.keepIsValid&&x()},xe=({disabled:L,name:Q,field:J,fields:we,value:me})=>{if(Fo(L)){const fe=L?void 0:Ht(me)?I0(J?J._f:ve(we,Q)._f):me;wt(s,Q,fe),A(Q,fe,!1,!1,!0)}},$e=(L,Q={})=>{let J=ve(o,L);const we=Fo(Q.disabled);return wt(o,L,{...J||{},_f:{...J&&J._f?J._f:{ref:{name:L}},name:L,mount:!0,...Q}}),u.mount.add(L),J?xe({field:J,disabled:Q.disabled,name:L}):M(L,!0,Q.value),{...we?{disabled:Q.disabled}:{},...n.progressive?{required:!!Q.required,min:du(Q.min),max:du(Q.max),minLength:du(Q.minLength),maxLength:du(Q.maxLength),pattern:du(Q.pattern)}:{},name:L,onChange:Z,onBlur:Z,ref:me=>{if(me){$e(L,Q),J=ve(o,L);const fe=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,Re=BY(fe),ft=J._f.refs||[];if(Re?ft.find(ht=>ht===fe):fe===J._f.ref)return;wt(o,L,{_f:{...J._f,...Re?{refs:[...ft.filter(N0),fe,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:fe.type,name:L}}:{ref:fe}}}),M(L,!1,void 0,fe)}else J=ve(o,L,{}),J._f&&(J._f.mount=!1),(n.shouldUnregister||Q.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Ae=()=>n.shouldFocusError&&tp(o,H,u.mount),Me=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Q=>{Q.disabled=L},0,!1))},je=(L,Q)=>async J=>{J&&(J.preventDefault&&J.preventDefault(),J.persist&&J.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:fe}=await U();r.errors=me,we=fe}else await q(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,J)):(Q&&await Q({...r.errors},J),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Q={})=>{ve(o,L)&&(Ht(Q.defaultValue)?K(L,ve(i,L)):(K(L,Q.defaultValue),wt(i,L,Q.defaultValue)),Q.keepTouched||pn(r.touchedFields,L),Q.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Q.defaultValue?ae(L,ve(i,L)):ae()),Q.keepError||(pn(r.errors,L),p.isValid&&x()),g.state.next({...r}))},ct=(L,Q={})=>{const J=L?so(L):i,we=so(J),me=L&&!Fr(L)?we:i;if(Q.keepDefaultValues||(i=J),!Q.keepValues){if(Q.keepDirtyValues||y)for(const fe of u.mount)ve(r.dirtyFields,fe)?wt(me,fe,ve(s,fe)):K(fe,ve(me,fe));else{if(Wx&&Ht(L))for(const fe of u.mount){const Re=ve(o,fe);if(Re&&Re._f){const ft=Array.isArray(Re._f.refs)?Re._f.refs[0]:Re._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Q.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Q.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Q.keepSubmitCount?r.submitCount:0,isDirty:Q.keepDirty?r.isDirty:!!(Q.keepDefaultValues&&!ma(L,i)),isSubmitted:Q.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Q.keepDirtyValues?r.dirtyFields:Q.keepDefaultValues&&L?D0(i,L):{},touchedFields:Q.keepTouched?r.touchedFields:{},errors:Q.keepErrors?r.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Q)=>ct(ms(L)?L(s):L,Q);return{control:{register:$e,unregister:he,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:U,_getWatch:V,_getDirty:ae,_updateValid:x,_removeUnmounted:X,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:F,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Me,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:se,register:$e,handleSubmit:je,watch:Oe,setValue:K,getValues:ce,reset:Kt,resetField:Mt,clearErrors:Ue,unregister:he,setError:We,setFocus:(L,Q={})=>{const J=ve(o,L),we=J&&J._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Q.shouldSelect&&me.select())}},getFieldState:Ve}}function YY(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Go extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const O2=(e,t)=>{if(Zp(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new yi({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew hc({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:ze.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:ze.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:ze.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:ze.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:ze.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:ze.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:pe.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:ze.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class O1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class nm extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}nm.create=(e,t)=>new nm({getter:e,typeName:ze.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:ze.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:ze.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:ze.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Be(t,x=>g(x)),b=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:de(e.onClick,x=>{_(C=>!C),S&&(b.current=x.isPropagationStopped(),b.current||x.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!b.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Pe.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Be(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:de(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Be(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(F=>[F.updateAppState,F.settings,F.updateSettings,F.fileManagerState,F.setModel,F.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,b]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_}=ML({queryKey:["serverConfig"],queryFn:gT}),x=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),x.setValue("removeBGModel",E.removeBGModel),x.setValue("realesrganModel",E.realesrganModel),x.setValue("interactiveSegModel",E.interactiveSegModel))},[x,E]);async function C(F){s({enableDownloadMask:F.enableDownloadMask,enableManualInpainting:F.enableManualInpainting,enableUploadMask:F.enableUploadMask,enableAutoExtractPrompt:F.enableAutoExtractPrompt});const N=p.name!==i.model.name,ie=(E==null?void 0:E.removeBGModel)!==F.removeBGModel&&M,K=(E==null?void 0:E.realesrganModel)!==F.realesrganModel&&A,Z=(E==null?void 0:E.interactiveSegModel)!==F.interactiveSegModel&&D;if(N||ie||K||Z){const se=[];if(N&&se.push(`Switching model from ${i.model.name} to ${p.name}`),ie&&se.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${F.removeBGModel}`),K&&se.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${F.realesrganModel}`),Z&&se.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${F.interactiveSegModel}`),b(se),o({disableShortCuts:!0}),N)try{const ce=await Bj(p.name);m({title:`Switch to ${ce.name} success`}),u(p)}catch(ce){m({variant:"destructive",title:`Switch to ${p.name} failed: ${ce}`}),g(i.model)}if(ie)try{const ce=await v0(Ao.RemoveBG,F.removeBGModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RemoveBG model to ${F.removeBGModel} failed: ${ce}`})}if(K)try{const ce=await v0(Ao.RealESRGAN,F.realesrganModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RealESRGAN model to ${F.realesrganModel} failed: ${ce}`})}if(Z)try{const ce=await v0(Ao.InteractiveSeg,F.interactiveSegModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${F.interactiveSegModel} failed: ${ce}`})}b([]),o({disableShortCuts:!1})}}if(Zn("s",()=>{t(),e&&C(x.getValues())},[e,x,p,E]),_!=="success")return v.jsx(v.Fragment,{});const R=E.modelInfos,P=E.plugins,M=P.some(F=>F.name===Ao.RemoveBG),A=P.some(F=>F.name===Ao.RealESRGAN),D=P.some(F=>F.name===Ao.InteractiveSeg);function U(F){t(),F||C(x.getValues())}function W(F){g(F)}function q(F){return R?R.filter(N=>F.includes(N.model_type)).map(N=>v.jsxs("div",{onClick:()=>W(N),className:"px-2",children:[v.jsx("div",{className:Ce([N.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:N.name})}),v.jsx(gn,{className:"my-1"})]},N.name)):v.jsx("div",{children:"Please download model first"})}function X(){let F=fs;for(let N of R)if(p.name===N.name){F=N.model_type,F===oC&&(F=uh),F===iC&&(F=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:F,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:q([fs])}),v.jsx(Su,{value:uh,children:q([uh,oC])}),v.jsx(Su,{value:dh,children:q([dh,iC])}),v.jsx(Su,{value:d0,children:q([d0])})]})]})]})]})}function ae(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"enableManualInpainting",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableDownloadMask",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableAutoExtractPrompt",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})})]})}function V(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"removeBGModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!M,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"realesrganModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"interactiveSegModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y.map((F,N)=>v.jsx("div",{children:F},N))]})})})}),v.jsxs(Jm,{open:e,onOpenChange:U,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:F=>F.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(F=>v.jsx(wn,{variant:"ghost",onClick:()=>r(F),className:Ce(n===F?"bg-muted ":"hover:bg-muted","justify-start"),children:F},F))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...x,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:x.handleSubmit(C),children:[n===F1?X():v.jsx(v.Fragment,{}),n===S3?ae():v.jsx(v.Fragment,{}),n===_3?V():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>U(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:b}=Id(),[S,E]=Px(t),[_,x]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const D=await Vj(M,A);l(D)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await gF(M)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){b({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var b=l+m*y,S=u+p*y,E=f+g*y;i(b,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),b=j1(t,u-g,m+g,r);return{x:y,y:b}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,b=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,x=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,x,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,b=g.y;e.setTransformState(f,y,b)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,b=u-o,S=m*m+p*p,E=Math.sqrt(S)/b;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,b=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,x=E.lockAxisX,C=S.animationType,R=b.sizeX,P=b.sizeY,M=b.velocityAlignmentTime,A=M,D=kZ(e,u),U=Math.max(D,A),W=sm(e,R),q=sm(e,P),X=W*o.offsetWidth/100,ae=q*o.offsetHeight/100,V=f+X,F=m-X,N=p+ae,ie=g-ae,K=e.transformState,Z=new Date().getTime();$3(e,C,U,function(H){var se=e.transformState,ce=se.scale,Ve=se.positionX,Ue=se.positionY,We=new Date().getTime()-Z,Oe=We/A,he=E3[b.animationType],xe=1-he(Math.min(1,Oe)),$e=1-H,Ae=Ve+s*$e,Me=Ue+l*$e,je=I2(Ae,K.positionX,Ve,x,y,m,f,F,V,xe),Mt=I2(Me,K.positionY,Ue,_,y,g,p,ie,N,xe);(Ve!==Ae||Ue!==Me)&&e.setTransformState(ce,je,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,b=n||o.offsetHeight/2,S=Qx(e,s,y,b);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,b=s.smooth,S=p.size,E=p.disabled,_=g.step,x=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=b?x*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var M=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,U=f&&D,W=fg(e,A.x,A.y,P,M,U),q=W.x,X=W.y;e.previousWheelEvent=t,e.setTransformState(P,q,X),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var b=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,b,E),x=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,x,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,b=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var x=N3(t,i,s),C=Qx(e,_,x.x,x.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,b,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(Jx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,b=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,x=E.current;return _!==null&&x!==null&&y&&(y==null||y(_,x)),function(){b==null||b()}},[]),Fe.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),Fe.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...b}=e,[S,E]=d.useState(null),_=Be(t,V=>E(V)),x=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,M=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:V=>{var F;(F=[...x.current][C.current])===null||F===void 0||F.focus(),p(V)}}),U=d.useRef(A);function W(V){const F=Pq(A,V);ae(V,F)}function q(V){ae(V,C.current)}function X(){const V=U.current[C.current];A[C.current]!==V&&g(A)}function ae(V,F,{commit:N}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((V-r)/i)*i+r,ie),Z=fd(K,[r,o]);D((H=[])=>{const se=kq(H,Z,F);if(Oq(se,u*i)){C.current=se.indexOf(Z);const ce=String(se)!==String(H);return ce&&N&&g(se),ce?se:H}else return H})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:x.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},b,{ref:_,onPointerDown:de(b.onPointerDown,()=>{l||(U.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:W,onSlideMove:l?void 0:q,onSlideEnd:l?void 0:X,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:F})=>{if(!l){const K=L3.includes(V.key)||V.shiftKey&&F3.includes(V.key)?10:1,Z=C.current,H=A[Z],se=i*K*F;ae(H+se,Z,{commit:!0})}}})))),P&&A.map((V,F)=>d.createElement(Rq,{key:F,name:n?n+(A.length>1?"[]":""):void 0,value:V})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Be(t,C=>g(C)),b=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function x(C){const R=b.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return b.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=x(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=x(C.clientX);l==null||l(R)},onSlideEnd:()=>{b.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Be(t,m),g=d.useRef(),y=!o;function b(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=b(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=b(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Pe.span,Y({},f,{ref:t,onKeyDown:de(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:de(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:de(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:de(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Be(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Be(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Be(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),b=m==null?void 0:m[s.size],S=b?Aq(b,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:de(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:b},S,E,_,x,C,R]=bt(H=>[H.imageWidth,H.imageHeight,H.isInpainting,H.isSD(),H.cropperState,H.setCropperX,H.setCropperY,H.setCropperWidth,H.setCropperHeight,H.isCropperExtenderResizing,H.setIsCropperExtenderResizing]),[P,M]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),U=()=>{},W=(H,se)=>W2(H,se,p,y,n,o),q=(H,se)=>W2(H,se,g,b,t,r),X=H=>{if(f)return;const se=H.clientX,ce=H.clientY,Ve=Math.round((ce-A.startResizeY)/i),Ue=Math.round((se-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Me,je]=q(Ae,$e);x(je),E(Me)},Oe=()=>{const $e=A.initHeight+Ve,[Ae,Me]=q(A.initY,$e);x(Me),E(Ae)},he=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Me,je]=W(Ae,$e);_(je),S(Me)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Me]=W(A.initX,$e);_(Me),S(Ae)};if(C)switch(A.ord){case"topleft":{We(),he();break}case"topright":{We(),xe();break}case"bottomleft":{Oe(),he();break}case"bottomright":{Oe(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Oe();break}case"left":{he();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Me,je]=W($e,A.initWidth),[Mt,ct]=q(Ae,A.initHeight);_(je),x(ct),S(Me),E(Mt)}},ae=()=>{C&&R(!1),P&&M(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",X,ll),document.addEventListener("pointerup",ae,ll),document.addEventListener("pointercancel",ae,ll),()=>{document.removeEventListener("pointermove",X,ll),document.removeEventListener("pointerup",ae,ll),document.removeEventListener("pointercancel",ae,ll)}},[C,P,y,b,A]);const V=H=>{const{ord:se}=H.target.dataset;se&&(R(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:se}))},F=(H,se,ce)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Oe="0",he="0",xe=ce,$e="-6px";return ce===""&&($e="50%",se==="left"||se==="right"?(xe="top",he="-50%"):(xe="left",Oe="-50%")),v.jsx("div",{className:Ce(We,H),style:{[se]:-6,[xe]:$e,transform:`translate(${Oe}, ${he}) scale(${1/i})`},"data-ord":se+ce,"aria-label":se+ce,tabIndex:-1,role:"button"})},N=()=>v.jsxs("div",{onFocus:U,onPointerDown:V,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),F("cursor-nw-resize","top","left"),F("cursor-ne-resize","top","right"),F("cursor-sw-resize","bottom","left"),F("cursor-se-resize","bottom","right"),F("cursor-ns-resize","top",""),F("cursor-ns-resize","bottom",""),F("cursor-ew-resize","left",""),F("cursor-ew-resize","right","")]}),ie=H=>{M(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:""})},K=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",b]}),Z=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:b,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:b,width:y,left:p,top:g},children:[Z(),K(),N()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,b,S,E,_,x,C]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>H2(ie,K,f,n),D=(ie,K)=>H2(ie,K,m,t),U=ie=>{if(i)return;const K=ie.clientX,Z=ie.clientY,H=Math.round((Z-R.startResizeY)/r),se=Math.round((K-R.startResizeX)/r),ce=()=>{const Oe=R.initHeight-H,he=R.initY+H;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initHeight-Math.abs(R.initY));else{const Ae=D(he,Oe);xe=Ae[0],$e=Ae[1]}E($e),b(xe)},Ve=()=>{const Oe=R.initHeight+H;let[he,xe]=D(R.initY,Oe);_===Ln.xy&&xe{const Oe=R.initWidth-se,he=R.initX+se;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initWidth-Math.abs(R.initX));else{const Ae=A(he,Oe);xe=Ae[0],$e=Ae[1]}S($e),y(xe)},We=()=>{const Oe=R.initWidth+se;let[he,xe]=A(R.initX,Oe);_===Ln.xy&&xe{x&&C(!1)};d.useEffect(()=>{if(x)return document.addEventListener("pointermove",U,cl),document.addEventListener("pointerup",W,cl),document.addEventListener("pointercancel",W,cl),()=>{document.removeEventListener("pointermove",U,cl),document.removeEventListener("pointerup",W,cl),document.removeEventListener("pointercancel",W,cl)}},[x,p,g,R]);const q=ie=>{const{ord:K}=ie.target.dataset;K&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},X=(ie,K,Z)=>{const ce="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Z,Oe="-6px";return Z===""&&(Oe="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ce,ie),style:{[K]:-6,[We]:Oe,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Z,"aria-label":K+Z,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:q,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),X("cursor-ns-resize","top",""),X("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),X("cursor-ew-resize","left",""),X("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[X("cursor-nw-resize","top","left"),X("cursor-ne-resize","top","right"),X("cursor-sw-resize","bottom","left"),X("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),V=ie=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},F=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:V,children:[p," x ",g]}),N=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[N(),F(),ae()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A,D]=bt(G=>[G.disableShortCuts,G.windowSize,G.isInpainting,G.imageWidth,G.imageHeight,G.settings,G.serverConfig.enableAutoSaving,G.setImageSize,G.setBaseBrushSize,G.interactiveSegState,G.updateInteractiveSegState,G.handleCanvasMouseDown,G.handleCanvasMouseMove,G.undo,G.redo,G.undoDisabled(),G.redoDisabled(),G.getIsProcessing(),G.updateAppState,G.runMannually(),G.runInpainting,G.isCropperExtenderResizing]),U=bt(G=>G.editorState.baseBrushSize),W=bt(G=>G.getBrushSize()),q=bt(G=>G.editorState.renders),X=bt(G=>G.editorState.extraMasks),ae=bt(G=>G.editorState.temporaryMasks),V=bt(G=>G.editorState.lineGroups),F=bt(G=>G.editorState.curLineGroup),[N,ie]=d.useState(!1),[K,Z]=Px(t),[H,se]=d.useState(),[ce,Ve]=d.useState(),[{x:Ue,y:We},Oe]=d.useState({x:-1,y:-1}),[he,xe]=d.useState(!1),[$e,Ae]=d.useState(!1),[Me,je]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Q=o.height/2,J=d.useRef(null),[we,me]=d.useState(!1),[fe,Re]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>F.length!==0,[F]);d.useEffect(()=>{if(!ce||!Z||s===0||l===0)return;const G=q.length===0?K:q[q.length-1];ce.canvas.width=s,ce.canvas.height=l,ce.clearRect(0,0,ce.canvas.width,ce.canvas.height),ce.drawImage(G,0,0,s,l)},[q,K,Z,ce,l,s]),d.useEffect(()=>{!H||!Z||s===0||l===0||(H.canvas.width=s,H.canvas.height=l,H.clearRect(0,0,H.canvas.width,H.canvas.height),ae.forEach(G=>{H.drawImage(G,0,0,s,l)}),X.forEach(G=>{H.drawImage(G,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&H.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(H,F))},[ae,X,Z,g,H,F,l,s]);const Cr=d.useCallback(async()=>{let G=t;if(q.length>0){const Ye=q[q.length-1];G=await Nu(Ye.currentSrc,t.name,t.type)}return G},[t,q]),Ni=()=>q.length!==0,Co=d.useCallback(()=>{let G=512,Ye=512;return Z?(q.length===0?(G=K.naturalWidth,Ye=K.naturalHeight):q.length!==0&&(G=q[q.length-1].width,Ye=q[q.length-1].height),[G,Ye]):[G,Ye]},[K,Z,q]);d.useEffect(()=>{var tf;if(!Z)return;const[G,Ye]=Co();(G!==s||Ye!==l)&&m(G,Ye);const st=o.width/G,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${G}x${Ye}, scale: ${an}, initialCentered: ${we}`),H!=null&&H.canvas&&(console.log("[on file load] set canvas size"),G!=H.canvas.width&&(H.canvas.width=G),Ye!=H.canvas.height&&(H.canvas.height=Ye)),we||((tf=J.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[J,l,s,K,Z,o,we,Co]),d.useEffect(()=>{var G;console.log("[useEffect] centerView"),(G=J==null?void 0:J.current)==null||G.centerView(gt,1)},[l,s,J,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const G=J.current;if(!G)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;G.setTransform(Ye,st,gt,200,"easeOutQuad"),G.instance.transformState.scale&&(G.instance.transformState.scale=gt),ct(gt),Er(!1)},[J,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(fe?Re(!1):Vn())},[fe,i,Vn]);const Di=G=>{const Ye=G.nativeEvent;Oe({x:Ye.pageX,y:Ye.pageY})},Ws=G=>{R||g.isInteractiveSeg||Me||fe&&F.length!==0&&S(f0(G))},Ii=async G=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,G),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=G=>{if(dC(G)){je(!1);return}!_n()||g.isInteractiveSeg||Me||!K.src||!(H!=null&&H.canvas)||i||fe&&(M?Re(!1):A())},bg=G=>{if(g.isInteractiveSeg){const Ye=f0(G),st=[...g.clicks];uC(G)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=G=>{if(!(R||g.isInteractiveSeg||Me||!Z||!(H!=null&&H.canvas))&&!uC(G)){if(dC(G)){je(!0);return}Re(!0),b(f0(G))}},Jd=G=>{G.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=G=>{G.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&q.length>0){try{await Hj(q[q.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const G=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=q[q.length-1];if(bF(Ye.currentSrc,G),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,V),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,q,u,l,s,V]);Zn("meta+s,ctrl+s",Nc);const Dc=G=>{G!==he&&!Me&&!D&&xe(G)},_g=d.useCallback(()=>{if(R)return"default";if(Me)return"grab";if(he)return"none"},[he,Me,R]);Zn("[",()=>{let G=U;U>10&&(G=U-10),U<=10&&U>0&&(G=U-5),p(G)},[U]),Zn("]",()=>{p(U+10)},[U]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&q.length>0&&H!=null&&H.canvas&&(await xF(H==null?void 0:H.canvas),n({title:"Copy inpainting result to clipboard"}))},[q,H]),s2(" ",G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!1),je(!0))},G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!0),je(!1))});const Ic=()=>{var Ye,st,Qr,an;let G=gt;return((st=(Ye=J.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(G=(an=(Qr=J.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),G},ef=(G,Ye)=>{const st=Ic();return{width:`${W*st}px`,height:`${W*st}px`,left:`${G}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=G=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:G}),Eg=G=>{p(G),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:G=>{G&&(J.current=G)},panning:{disabled:!Me,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:G=>{ct(G.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:G=>{if(G&&!ce){const Ye=G.getContext("2d");Ye&&Ve(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:G=>{G.preventDefault()},onMouseOver:()=>{Dc(!0),Ae(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:G=>{if(G&&!H){const Ye=G.getContext("2d");Ye&&se(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:N&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),he&&!i&&!Me&&(g.isInteractiveSeg?Cg():Lc(ef(Ue,We))),$e&&Lc(ef(L,Q)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[U],onValueChange:G=>Eg(G[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:x,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:G=>{G.preventDefault(),ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu)},disabled:q.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!q.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&X.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:b,...S}=e,E=Us(bo,n),_=Qd(bo,n),x=gg(n),C=Y3(n),R=nQ(n),[P,M]=d.useState(null),A=d.useRef(null),D=Be(t,A,E.onContentChange),U=d.useRef(0),W=d.useRef(""),q=d.useRef(0),X=d.useRef(null),ae=d.useRef("right"),V=d.useRef(0),F=b?qm:d.Fragment,N=b?{as:Zo,allowPinchZoom:!0}:void 0,ie=Z=>{var H,se;const ce=W.current+Z,Ve=R().filter($e=>!$e.disabled),Ue=document.activeElement,We=(H=Ve.find($e=>$e.ref.current===Ue))===null||H===void 0?void 0:H.textValue,Oe=Ve.map($e=>$e.textValue),he=kQ(Oe,ce,We),xe=(se=Ve.find($e=>$e.textValue===he))===null||se===void 0?void 0:se.ref.current;(function $e(Ae){W.current=Ae,window.clearTimeout(U.current),Ae!==""&&(U.current=window.setTimeout(()=>$e(""),1e3))})(ce),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(U.current),[]),Xm();const K=d.useCallback(Z=>{var H,se;return ae.current===((H=X.current)===null||H===void 0?void 0:H.side)&&PQ(Z,(se=X.current)===null||se===void 0?void 0:se.area)},[]);return d.createElement(lQ,{scope:n,searchRef:W,onItemEnter:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),onItemLeave:d.useCallback(Z=>{var H;K(Z)||((H=A.current)===null||H===void 0||H.focus(),M(null))},[K]),onTriggerLeave:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),pointerGraceTimerRef:q,onPointerGraceIntentChange:d.useCallback(Z=>{X.current=Z},[])},d.createElement(F,N,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:de(i,Z=>{var H;Z.preventDefault(),(H=A.current)===null||H===void 0||H.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:de(u,Z=>{_.isUsingKeyboardRef.current||Z.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},x,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:de(S.onKeyDown,Z=>{const se=Z.target.closest("[data-radix-menu-content]")===Z.currentTarget,ce=Z.ctrlKey||Z.altKey||Z.metaKey,Ve=Z.key.length===1;se&&(Z.key==="Tab"&&Z.preventDefault(),!ce&&Ve&&ie(Z.key));const Ue=A.current;if(Z.target!==Ue||!Jq.includes(Z.key))return;Z.preventDefault();const Oe=R().filter(he=>!he.disabled).map(he=>he.ref.current);K3.includes(Z.key)&&Oe.reverse(),$Q(Oe)}),onBlur:de(e.onBlur,Z=>{Z.currentTarget.contains(Z.target)||(window.clearTimeout(U.current),W.current="")}),onPointerMove:de(e.onPointerMove,gd(Z=>{const H=Z.target,se=V.current!==Z.clientX;if(Z.currentTarget.contains(H)&&se){const ce=Z.clientX>V.current?"right":"left";ae.current=ce,V.current=Z.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Be(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:de(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:de(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:de(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Be(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const b=u.current;if(b){var S;y(((S=b.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Pe.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:de(e.onPointerMove,gd(b=>{r?s.onItemLeave(b):(s.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus())})),onPointerLeave:de(e.onPointerLeave,gd(b=>s.onItemLeave(b))),onFocus:de(e.onFocus,()=>p(!0)),onBlur:de(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:de(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Pe.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:de(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var b;const S=(b=n.content)===null||b===void 0?void 0:b.dataset.side,E=S==="right",_=E?-5:5,x=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Be(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:de(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:de(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Pe.button,Y({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:Nm(t,i.triggerRef),onPointerDown:de(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:de(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:de(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(N=>[N.serverConfig.samplers,N.settings,N.paintByExampleFile,N.getIsProcessing(),N.updateSettings,N.runInpainting,N.updateAppState,N.updateExtenderByBuiltIn,N.updateExtenderDirection,N.adjustMask,N.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const b=N=>{N.key==="Enter"&&N.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:N=>{o({showCropper:N}),N&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:N=>{o({enableControlnet:N})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:N=>o({controlnetConditioningScale:N[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:N=>{o({controlnetConditioningScale:N})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:N=>{o({controlnetMethod:N})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(N=>v.jsx(yo,{value:N,children:N.split("/")[1]},N))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:N=>{o({enableLCMLora:N})}})]}),v.jsx(gn,{})]}):null,x=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:N=>{o({enableFreeu:N})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s2:N}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b2:N}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:b,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:N=>{N.preventDefault(),N.stopPropagation();const ie=N.target;o({negativePrompt:ie.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:N=>{s({paintByExampleFile:N})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:N=>o({p2pImageGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({p2pImageGuidanceScale:N})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:N=>o({sdStrength:N[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:N=>{o({sdStrength:N})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:N=>{o({showExtender:N}),N&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:N=>{u(N)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(N=>v.jsx(yo,{value:N,children:N},N))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:N=>{o({powerpaintTask:N})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]}),U=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:N=>o({sdSteps:N[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:N=>{o({sdSteps:N})}})]})]}),W=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:N=>o({sdGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({sdGuidanceScale:N})}})]})]}),q=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:N=>{o({sdSampler:N})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(N=>v.jsx(yo,{value:N,className:"text-xs",children:N},N))})})]})]}),X=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:N=>{o({seedFixed:N})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:N=>{o({seed:N})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:N=>o({sdMaskBlur:N[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:N=>{o({sdMaskBlur:N})}})]})]}),V=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:N=>{o({sdMatchHistograms:N})}})]}),v.jsx(gn,{})]}),F=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:N=>o({adjustMaskKernelSize:N[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:N=>{o({adjustMaskKernelSize:N})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),F(),D(),U(),W(),P(),M(),q(),X(),C(),v.jsx(gn,{}),E(),_(),ae(),V(),x(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=TA()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Xo extends qt{constructor(t,n){super(),vg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=r$?{}:RA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{n$&&this.ws.send(i)}catch{}o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=X1(n.host).host),vg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=$A,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){hl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ac.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,vg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){lb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new NA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Pe.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Be(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),b=s.toastCount>0;d.useEffect(()=>{const E=_=>{var x;r.every(R=>_[R]||_.code===R)&&((x=p.current)===null||x===void 0||x.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(b&&E&&_){const x=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(ew);_.dispatchEvent(M),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(tw);_.dispatchEvent(M),s.isClosePausedRef.current=!1}},R=M=>{!E.contains(M.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",x),E.addEventListener("focusout",R),E.addEventListener("pointermove",x),E.addEventListener("pointerleave",P),window.addEventListener("blur",x),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",x),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",x),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",x),window.removeEventListener("focus",C)}}},[b,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const x=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?x.reverse():x).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=x=>{const C=x.altKey||x.ctrlKey||x.metaKey;if(x.key==="Tab"&&!C){const D=document.activeElement,U=x.shiftKey;if(x.target===E&&U){var P;(P=f.current)===null||P===void 0||P.focus();return}const X=S({tabbingDirection:U?"backwards":"forwards"}),ae=X.findIndex(V=>V===D);if(U0(X.slice(ae+1)))x.preventDefault();else{var M,A;U?(M=f.current)===null||M===void 0||M.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:b?void 0:"none"}},b&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),b&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:de(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:de(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:de(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:de(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...b}=e,S=wg(xg,n),[E,_]=d.useState(null),x=Be(t,V=>_(V)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,M=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:U,onToastRemove:W}=S,q=Ft(()=>{var V;(E==null?void 0:E.contains(document.activeElement))&&((V=S.viewport)===null||V===void 0||V.focus()),s()}),X=d.useCallback(V=>{!V||V===1/0||(window.clearTimeout(D.current),M.current=new Date().getTime(),D.current=window.setTimeout(q,V))},[q]);d.useEffect(()=>{const V=S.viewport;if(V){const F=()=>{X(A.current),f==null||f()},N=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(D.current),u==null||u()};return V.addEventListener(ew,N),V.addEventListener(tw,F),()=>{V.removeEventListener(ew,N),V.removeEventListener(tw,F)}}},[S.viewport,P,u,f,X]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&X(P)},[i,P,S.isClosePausedRef,X]),d.useEffect(()=>(U(),()=>W()),[U,W]);const ae=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,ae&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),d.createElement(Vee,{scope:n,onClose:q},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:de(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||q(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},b,{ref:x,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:de(e.onKeyDown,V=>{V.key==="Escape"&&(l==null||l(V.nativeEvent),V.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,q()))}),onPointerDown:de(e.onPointerDown,V=>{V.button===0&&(C.current={x:V.clientX,y:V.clientY})}),onPointerMove:de(e.onPointerMove,V=>{if(!C.current)return;const F=V.clientX-C.current.x,N=V.clientY-C.current.y,ie=!!R.current,K=["left","right"].includes(S.swipeDirection),Z=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,H=K?Z(0,F):0,se=K?0:Z(0,N),ce=V.pointerType==="touch"?10:2,Ve={x:H,y:se},Ue={originalEvent:V,delta:Ve};ie?(R.current=Ve,Th(jee,p,Ue,{discrete:!1})):s$(Ve,S.swipeDirection,ce)?(R.current=Ve,Th(Fee,m,Ue,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(F)>ce||Math.abs(N)>ce)&&(C.current=null)}),onPointerUp:de(e.onPointerUp,V=>{const F=R.current,N=V.target;if(N.hasPointerCapture(V.pointerId)&&N.releasePointerCapture(V.pointerId),R.current=null,C.current=null,F){const ie=V.currentTarget,K={originalEvent:V,delta:F};s$(F,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,K,{discrete:!0}):Th(zee,g,K,{discrete:!0}),ie.addEventListener("click",Z=>Z.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],b=y.type;ote.includes(b)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,b=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(b.length===0)return;g.preventDefault(),g.stopPropagation();const E=b[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?Fe.createElement(d.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,b]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const M=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),M&&D.classList.add(M)):M?D.setAttribute(l,M):D.removeAttribute(l),r){const U=cm.includes(s)?s:null,W=cm.includes(P)?P:U;D.style.colorScheme=W}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),x=d.useCallback(R=>{const P=l$(R);b(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(x),x(R),()=>R.removeListener(x)},[x]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return Fe.createElement(sM.Provider,{value:C},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(b=>`'${b}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(b,S=!1,E=!0)=>{const _=s?s[b]:b,x=S?b+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(b)&&(C+=`d.style.colorScheme = '${b}';`),n==="class"?C+=S||_?`c.add(${x})`:"null":_&&(C+=`d[s](n,${x})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-hrusMZZs.js b/py/iopaint/web_app/assets/index-hrusMZZs.js new file mode 100644 index 0000000..7a05f8a --- /dev/null +++ b/py/iopaint/web_app/assets/index-hrusMZZs.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var wn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){wn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];wn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){wn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){wn[e]=new Un(e,2,!1,e,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(e){wn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){wn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){wn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){wn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){wn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);wn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});wn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){wn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=wn.hasOwnProperty(t)?wn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:En,useContext:En,useEffect:En,useImperativeHandle:En,useInsertionEffect:En,useLayoutEffect:En,useMemo:En,useReducer:En,useRef:En,useState:En,useDebugValue:En,useDeferredValue:En,useTransition:En,useMutableSource:En,useSyncExternalStore:En,useId:En,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Cn(t),null}else 2*Zt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Zt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Cn(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Cn(t),t.subtreeFlags&6&&(t.flags|=8192)):Cn(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,kn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:kn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!kn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!kn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(kn=(r=kn)||n.memoizedState!==null,ji(e,t,n),kn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Zt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uZt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,$n,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,$n,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,$n,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,$n,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,$n)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,$n)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,$n),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,$n),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,$n,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,$n)).some(d=>{const h=d;return z(this,$n)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,$n=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,$n).isStale||!My(this.options.staleTime))return;const n=PR(z(this,$n).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,$n).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,$n))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function uF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function dF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function fF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function pF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function hF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const mF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function gF(e){const t=await hF(e,"image/png");try{await mF(t)}catch{console.log("Copy image failed!")}}function vF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:yF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=yF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function wF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function xF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const bF=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",_F=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},SF=Go("Date"),EF=Go("File"),CF=Go("Blob"),$F=Go("FileList"),kF=e=>Rm(e)&&Kr(e.pipe),RF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},TF=Go("URLSearchParams"),PF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),OF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),MF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},NF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},DF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},IF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},LF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),FF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},jF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},zF=Go("HTMLFormElement"),BF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),UF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},VF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},WF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},HF=()=>{},KF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},YF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function GF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const XF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ZF=Go("AsyncFunction"),qF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:wF,isFormData:RF,isArrayBufferView:xF,isString:bF,isNumber:qR,isBoolean:_F,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:SF,isFile:EF,isBlob:CF,isRegExp:UF,isFunction:Kr,isStream:kF,isURLSearchParams:TF,isTypedArray:LF,isFileList:$F,forEach:kd,merge:Yy,extend:AF,trim:PF,stripBOM:OF,inherits:MF,toFlatObject:NF,kindOf:$m,kindOfTest:Go,endsWith:DF,toArray:IF,forEachEntry:FF,matchAll:jF,isHTMLForm:zF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:VF,toObjectSet:WF,toCamelCase:BF,noop:HF,toFiniteNumber:KF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:YF,isSpecCompliantForm:GF,toJSONObject:XF,isAsyncFn:ZF,isThenable:qF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const QF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function JF(e){return oe.isArray(e)&&!e.some(Gy)}const ej=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&JF(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(ej,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function tj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||tj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class nj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=nj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},rj=typeof URLSearchParams<"u"?URLSearchParams:tx,oj=typeof FormData<"u"?FormData:null,ij=typeof Blob<"u"?Blob:null,sj={isBrowser:!0,classes:{URLSearchParams:rj,FormData:oj,Blob:ij},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",aj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),lj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",cj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:aj,hasStandardBrowserWebWorkerEnv:lj},Symbol.toStringTag,{value:"Module"})),Io={...cj,...sj};function uj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function dj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function fj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=fj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(dj(r),o,n,0)}),n}return null}function pj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return uj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),pj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,hj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),mj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&hj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function gj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const vj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function yj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function wj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!vj(t)?s(mj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return gj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?yj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(wj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function xj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const bj=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function _j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Sj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!_j(t)?Sj(e,t):t}const Ej=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Cj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function $j(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const kj=typeof XMLHttpRequest<"u",Rj=kj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};xj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Ej(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&bj.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=Cj(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:QF,xhr:Rj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Tj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Pj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Pj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Aj=ix;function Oj(e){return function(n){return e.apply(null,n)}}function Mj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Nj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Jt=mT(rx);Jt.Axios=zp;Jt.CanceledError=Rd;Jt.CancelToken=Aj;Jt.isCancel=dT;Jt.VERSION=hT;Jt.toFormData=Tm;Jt.AxiosError=ut;Jt.Cancel=Jt.CanceledError;Jt.all=function(t){return Promise.all(t)};Jt.spread=Oj;Jt.isAxiosError=Mj;Jt.mergeConfig=Jl;Jt.AxiosHeaders=pi;Jt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Jt.getAdapter=pT.getAdapter;Jt.HttpStatusCode=Nj;Jt.default=Jt;const Dj=Jt,Ms="http://127.0.0.1:8080/api/v1",vc=Dj.create({baseURL:Ms});async function Ij(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Lj(){return(await vc.get("/server-config")).data}async function Fj(e){return(await vc.post("/model",{name:e})).data}async function jj(){return(await vc.get("/model")).data}function zj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Bj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Uj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Vj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Wj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Hj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Kj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Yj=["color"],Gj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Yj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Xj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Xj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,ez);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,nz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],oz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),iz=["color"],sz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,iz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),az=["color"],lz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,az);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,cz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,dz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>pz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(hz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...mz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function hz(e){return f.isValidElement(e)&&e.type===sx}function mz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var gz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function vz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},yz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},wz=(e,t)=>(n,r,o)=>{let i={storage:vz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},xz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((gz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),yz(e,t)):wz(e,t),bz=xz;function _z(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Ez(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Cz),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function Cz(){ho(2)}function Im(e){return Object.isFrozen(e)}var $z={};function ka(e){const t=$z[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function kz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Rz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=kz(Ju,e)}function Rz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Tz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Pz(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Ez(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Pz(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Az=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Oz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Tz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Oz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Az,Mz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Nz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Mz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Dz=Nz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Iz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Lz=typeof Object.is=="function"?Object.is:Iz,Fz=nc.useState,jz=nc.useEffect,zz=nc.useLayoutEffect,Bz=nc.useDebugValue;function Uz(e,t){var n=t(),r=Fz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return zz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),jz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Bz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Lz(e,n)}catch{return!0}}function Vz(e,t){return t()}var Wz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Vz:Uz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Wz;kT.exports=RT;var Hz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Kz=Hz;function Yz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Gz=typeof Object.is=="function"?Object.is:Yz,Xz=Kz.useSyncExternalStore,Zz=Lm.useRef,qz=Lm.useEffect,Qz=Lm.useMemo,Jz=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Zz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Qz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Gz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Xz(e,i[0],i[1]);return qz(function(){s.hasValue=!0,s.value=l},[l]),Jz(l),l};CT.exports=$T;var eB=CT.exports;const tB=lm(eB);var nB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(nB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},rB=e=>e?RC(e):RC,{useDebugValue:oB}=Fe,{useSyncExternalStoreWithSelector:iB}=tB;function sB(e,t=e.getState,n){const r=iB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return oB(r),r}const TC=(e,t)=>{const n=rB(e),r=(o,i=t)=>sB(n,o,i);return Object.assign(r,n),r},aB=(e,t)=>e?TC(e,t):TC,lB=1,cB=1e6;let v0=0;function uB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},cB);y0.set(e,t)},dB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,lB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=dB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=uB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:cF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=aB()(bz(Dz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Ij(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Wj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Hj(d,n,l),m=await dF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),_z),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function fB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,pB(o,...t)]}function pB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const hB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=hB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function mB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",gB="dismissableLayer.pointerDownOutside",vB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=wB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=xB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return mB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),yB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function wB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(gB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(vB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const bB=yc,_B=yB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},SB=jD.useId||(()=>{});let EB=0;function nr(e){const[t,n]=f.useState(SB());return Pn(()=>{e||n(r=>r??String(EB++))},[e]),e||(t?`radix-${t}`:"")}const CB=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),$B={left:"right",right:"left",bottom:"top",top:"bottom"},kB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function RB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function TB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>kB[t])}function PB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function AB(e,t,n,r){const o=wc(e);let i=PB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>$B[t])}function OB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?OB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const MB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return CB.some(t=>e[t]>=0)}const DB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function IB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const LB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await IB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},FB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},jB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},zB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function BB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function UB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const VB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?VB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function WB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=WB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function HB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function KB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function YB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function GB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function XB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=GB(e,n);else if(t==="document")r=YB(Ci(e));else if(xi(t))r=XB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function ZB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function qB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?ZB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function QB(e){return NT(e)}function JB(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&BB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||UB(e)||n}const eU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:JB(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function tU(e){return Xr(e).direction==="rtl"}const nU={convertOffsetParentRelativeRectToViewportRelativeRect:HB,getDocumentElement:Ci,getClippingRect:qB,getOffsetParent:FT,getElementRects:eU,getClientRects:KB,getDimensions:QB,getScale:Rl,isElement:xi,isRTL:tU};function rU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function oU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?rU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const iU=(e,t,n)=>{const r=new Map,o={platform:nU,...n},i={...o.platform,_c:r};return MB(e,t,{...o,platform:i})},sU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function aU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),iU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[lU,UT]=BT(zT),cU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(lU,{scope:t,anchor:r,onAnchorChange:o},n)},uU="PopperAnchor",dU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(uU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[fU,hte]=BT(VT),pU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Yt=>V(Yt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(hU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=aU({strategy:"fixed",placement:ie,whileElementsMounted:(...Yt)=>oU(...Yt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[LB({mainAxis:g+L,alignmentAxis:x}),C&&FB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?jB():void 0,...le}),C&&NB({...le}),zB({...le,apply:({elements:Yt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Yt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&sU({element:G,padding:_}),mU({arrowWidth:te,arrowHeight:L}),k&&DB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(fU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function hU(e){return e!==null}const mU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=cU,zm=dU,Bm=pU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function gU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const xn=e=>{const{present:t,children:n}=e,r=vU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};xn.displayName="Presence";function vU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=gU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=yU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function yU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),wU=Um,[Vm,mte]=An("Tooltip",[Ns]),vx=Ns(),xU="TooltipProvider",bU=700,l1="tooltip.open",[_U,yx]=Vm(xU),SU=e=>{const{__scopeTooltip:t,delayDuration:n=bU,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(_U,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[EU,Wm]=Vm(wx),CU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(EU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",$U=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),kU="TooltipPortal",[gte,RU]=Vm(kU,{forceMount:void 0}),rd="TooltipContent",TU=f.forwardRef((e,t)=>{const n=RU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(xn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(PU,Y({side:o},i,{ref:t})))}),PU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=OU(S,C.getBoundingClientRect()),E=MU(S,b),k=NU(_.getBoundingClientRect()),P=IU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!DU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[AU,vte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(AU,{scope:n,isInside:!0},f.createElement(wU,{id:u.contentId,role:"tooltip"},o||r))))});function OU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 MU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function NU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function DU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function IU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),LU(t)}function LU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const FU=SU,jU=CU,zU=$U,KT=TU,BU=FU,YT=jU,GT=zU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),Rn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});Rn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Rn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var UU={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"};const VU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Kt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...UU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${VU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},WU=Kt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),HU=Kt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),KU=Kt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),YU=Kt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),GU=Kt("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"}]]),XU=Kt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),ZU=Kt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),qU=Kt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),QU=Kt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Kt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),JU=Kt("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"}]]),eV=Kt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),tV=Kt("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),nV=Kt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Kt("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),oV=Kt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Kt("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"}]]),sV=Kt("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"}]]),VC=Kt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Kt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Kt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Kt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(cV(hV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=uV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const YC=pV();function pV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function hV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=OV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=tP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return MV(o)},[o]);return f.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return nP(e,"overflowY")},jV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?FV(t):jV(t)},oP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,Qa=[];function YV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(KV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=mV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return VV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&WV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:HV(o)}):null,y?f.createElement(IV,{gapMode:"margin"}):null)}const GV=EV(eP,YV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:GV}))});iP.classNames=Ym.classNames;const Gm=iP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[QV,bo]=lP(aP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},eW="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(eW,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[tW,fP]=lP(dP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(tW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",rW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(xn,{present:r||i.open},f.createElement(oW,Y({},o,{ref:t}))):null}),oW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",iW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(sW,Y({},o,{ref:t})):f.createElement(aW,Y({},o,{ref:t})))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),aW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",lW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(uW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const fW="DialogTitleWarning",[pW,yte]=fB(fW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=JV,gP=uP,Ex=nW,Nd=rW,Dd=iW,Id=lW,Ld=mP,Cx=dW,Zm=Sx,$x=gP,hW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(hW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const mW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var SW=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?yW(d):!d},EW=f.createContext(void 0),CW=function(){return f.useContext(EW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var $W=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),kW=function(){return f.useContext($W)};function RW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function PW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=RW(s),g=kW(),y=g.enabledScopes,x=CW();return TW(function(){if(!((m==null?void 0:m.enabled)===!1||!_W(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(bW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(SW(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(wW(k,F,m==null?void 0:m.preventDefault),!xW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>AW()?"Cmd":"Ctrl";function OW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(eV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,wte]=An(EP,[Ns]),Tx=Ns(),[MW,bc]=CP(EP),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(MW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(DW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[LW,FW]=CP($P,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(LW,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",zW=f.forwardRef((e,t)=>{const n=FW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(xn,{present:r||i.open},i.modal?f.createElement(BW,Y({},o,{ref:t})):f.createElement(UW,Y({},o,{ref:t})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,TP=zW,KW=VW,YW=WW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function GW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=GW();f.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(Rn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Dream"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Yt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",bn="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[bn]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Yt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[bn]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Yt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=Sn(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=_n(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=Sn(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Xt){var no=w,ri=$;return w=$=n,ne=Xt,N=a.apply(ri,no),N}function Ie(Xt){return ne=Xt,D=Hc(nt,c),re?Re(Xt):N}function Qe(Xt){var no=Xt-B,ri=Xt-ne,IS=c-no;return se?_n(IS,T-ri):IS}function Le(Xt){var no=Xt-B,ri=Xt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Xt=Of();if(Le(Xt))return at(Xt);D=Hc(nt,Qe(Xt))}function at(Xt){return D=n,me&&w?Re(Xt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Xt=Of(),no=Le(Xt);if(w=arguments,$=this,B=Xt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=_n(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Gt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=Sn(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Yt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&Sn(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=Sn(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return _n(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=_n(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var wH=Lh.exports;const xH=lm(wH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class _H{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function kH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function RH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=kH(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=RH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=CH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function OH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function MH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(MH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=FH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=LH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function zH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function YH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function GH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=f.useReducer(GH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(YH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,d=eK(e,l,u);return f.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&tK(e,d,u))}function rK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=f.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=f.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=f.forwardRef(cK),dK=uK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const fK=1/0;function pK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function hK(e){return e==null?"":pK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function gK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class _K{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function SK(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||mK(d)))n.push(hK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function OK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(wK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=AK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function MK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:MK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=OK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[NK,KP,IK,LK,jK,FK,DK,HP],u2=m1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),KK=e=>!!e[y1.PATH],YK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(YK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(yK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function GK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new _K(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(vK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=PK;_c.config=He;_c.parseQuery=YP;HK(WK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const QK=f.createContext(void 0);function Sc(e){const t=f.useContext(QK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,eY]=zd(Dx),[tY,Qm]=An(Dx,[eY]),[nY,rY]=tY(Dx),oY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(iY,Y({},e,{ref:t}))))),iY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(nY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,JK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),sY="RovingFocusGroupItem",aY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=rY(sY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=uY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?dY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),lY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uY(e,t,n){const r=cY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=oY,qP=aY,QP="Tabs",[fY,xte]=An(QP,[Qm]),JP=Qm(),[pY,Ix]=fY(QP),hY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(pY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),mY="TabsList",gY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(mY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vY="TabsTrigger",yY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(vY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),wY="TabsContent",xY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(wY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(xn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const bY=hY,n5=gY,r5=yY,o5=xY,i5=bY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const _Y=[" ","Enter","ArrowUp","ArrowDown"],SY=[" ","Enter"],Jm="Select",[eg,tg,EY]=zd(Jm),[Ec,bte]=An(Jm,[EY,Ns]),jx=Ns(),[CY,Oa]=Ec(Jm),[$Y,kY]=Ec(Jm),RY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(CY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement($Y,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},TY="SelectTrigger",PY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(TY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&_Y.includes(x.key)&&(y(),x.preventDefault())})})))}),AY="SelectValue",OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(AY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),MY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",DY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(IY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:LY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),LY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Yt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Yt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(FY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[FY,zx]=Ec(ic,{}),p2="SelectViewport",jY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),zY="SelectGroup",[BY,UY]=Ec(zY),VY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(BY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WY="SelectLabel",HY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UY(WY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[KY,a5]=Ec(b1),YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(KY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(SY.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",GY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=kY(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),XY="SelectItemIndicator",ZY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(XY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",qY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",QY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),JY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eG(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tG=RY,p5=PY,nG=OY,rG=MY,oG=NY,h5=DY,iG=jY,sG=VY,m5=HY,g5=YY,aG=GY,lG=ZY,v5=qY,y5=QY,w5=JY,aa=tG,wl=sG,la=nG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rG,{asChild:!0,children:v.jsx(Gj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(tz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(iG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(aG,{children:t})]}));us.displayName=g5.displayName;const uG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uG.displayName=w5.displayName;function dG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,_te]=An(_5),[fG,qr]=S5(_5),pG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(fG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),hG="ScrollAreaViewport",mG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(hG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(vG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(xn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=dG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(xn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return CG(g,s.current,l,y)}return n==="horizontal"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(wG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),wG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[xG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(xG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",bG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(xn,{present:n||o.hasThumb},f.createElement(_G,Y({ref:t},r)))}),_G=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=$G(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",SG=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(EG,Y({},e,{ref:t})):null}),EG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=pG,kG=mG,RG=SG,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(kG,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(RG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",TG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function PG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=lV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Uj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=xH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(fz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(uz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(QU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(sz,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:TG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,AG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(AG(t)),OG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!OG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),MG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LG=e=>e.render(IG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var FG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function jG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",BG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var UG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,VG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const KG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function YG(e={},t){let n={...KG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),HG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,UG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?FG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const bn=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!VG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||WG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,bn),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,bn,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(bn),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(bn),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=BG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Yt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Yt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Yt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function GG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...YG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},XG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qG(t.names||Object.keys(e),r)){var s=Object.assign({},ZG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},JG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XG(QG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Kh;function S1(){return eX}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new pX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class pX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const hX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",mX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return mX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const vX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=vX,yX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const wX=MG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(LG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const xX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const a3="Switch",[bX,Ste]=An(a3),[_X,SX]=bX(a3),EX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(_X,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement(kX,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=SX(CX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),kX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=EX,RX=$X,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(RX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const TX="AlertDialog",[PX,Ete]=An(TX,[cP]),Is=cP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},OX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},MX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[NX,DX]=PX(u3),IX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(pW,{contentName:u3,titleName:LX,docsSlug:"alert-dialog"},f.createElement(NX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),LX="AlertDialogTitle",FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),zX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),VX=AX,WX=OX,d3=MX,f3=IX,p3=zX,h3=UX,m3=FX,g3=jX,HX=VX,KX=WX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));YX.displayName=m3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));GX.displayName=g3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));XX.displayName=p3.displayName;const ZX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=h3.displayName;const qX=hX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",QX=[I1,x3];function JX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:zj}),S=GG({resolver:JG(qX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await Fj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(O=>v.jsx(Rn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(wX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(Rn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(YU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Bj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(JU,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await fF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(KW,{open:S,children:[v.jsx(YW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(lz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(OW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},pZ=function(e){return 1- --e*e*e*e},hZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:pZ,easeInOutQuart:hZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=xZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},_Z=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function SZ(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},kZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function RZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=TZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=kZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=RZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?_Z(e,t):bZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?AZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=KZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=YZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=GZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},JZ))},oq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=qZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=QZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(OZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=f.useRef(new uq(e)).current,r=dq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:VZ([n,t])}))});function pq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var hq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};pq(hq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,gq,vq]=zd(Wd),[L3,Cte]=An(Wd,[vq]),[yq,dg]=L3(Wd),wq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?xq:bq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Pq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=Rq(W,Q,te);if(Mq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement(kq,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),bq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),_q="SliderTrack",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(_q,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Eq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Cq=f.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement($q,Y({},e,{ref:i,index:s}))}),$q=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Tq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Aq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),kq=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function Rq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Oq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Mq(e,t){if(t>0){const n=Oq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=wq,Iq=Sq,Lq=Eq,Fq=Cq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},jq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(Rn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(Rn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),nl={capture:!0,passive:!1},Hq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Yq=200,Gq=10,Xq=200,lu=300;function Zq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Yt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),bn=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Yq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!bn())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Vj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(vF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&bn()&&A()},[M,A,bn]),Zn("ctrl+c,meta+c",async()=>{await pF()&&J.length>0&&W!=null&&W.canvas&&(await gF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),Sg=()=>v.jsx(fq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Yt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Gq,max:Xq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Yt===!1,onClick:Vn,children:v.jsx(ZU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(aV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(oV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(GU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!bn()&&G.length===0,onClick:()=>{A()},children:v.jsx(XU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Jq=[...Qq,...V3],eQ={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,nQ,rQ]=zd(fg),[Na,W3]=An(fg,[rQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[oQ,Hd]=Na(fg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(oQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[sQ,X3]=Na(G3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(sQ,{scope:t,forceMount:n},f.createElement(xn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[lQ,Jx]=Na(yo),cQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(uQ,Y({},o,{ref:t})):f.createElement(dQ,Y({},o,{ref:t})))))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=nQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=RQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&PQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(lQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Jq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),$Q(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),fQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),pQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),hQ="MenuRadioGroup",[$te,mQ]=Na(hQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,yQ]=Na(q3,{checked:!1}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(q3,n);return f.createElement(xn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),xQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[bQ,eA]=Na(J3),_Q=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",SQ=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&eQ[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),EQ="MenuSubContent",CQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(EQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(xn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=tQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function RQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=kQ(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,OQ=Y3,MQ=aQ,NQ=cQ,DQ=fQ,IQ=tb,LQ=pQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=_Q,UQ=SQ,VQ=CQ,nA="DropdownMenu",[WQ,kte]=An(nA,[W3]),Sr=W3(),[HQ,rA]=WQ(nA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(AQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},YQ="DropdownMenuTrigger",GQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(YQ,n),s=Sr(n);return f.createElement(OQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(MQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(ZQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=GQ,cJ=XQ,oA=qQ,iA=QQ,sA=JQ,aA=eJ,lA=tJ,cA=nJ,uA=rJ,uJ=oJ,dA=iJ,fA=sJ,dJ=aJ,fJ=lJ,K2=uJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(Jj,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const pJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));pJ.displayName=aA.displayName;const hJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(oz,{className:"h-4 w-4 fill-current"})})}),t]}));hJ.displayName=lA.displayName;const mJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=iA.displayName;const gJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(WU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},yJ=Sx,wJ=gP,xJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const bJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));_J.displayName=Id.displayName;const SJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));SJ.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(Rn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(Rn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM Lora",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(Rn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(rV,{size:16}),"expand"]})}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsxs("div",{className:"flex items-center gap-1 select-none",children:[v.jsx(tV,{size:16}),"Shrink"]})})]}),v.jsx(Rn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},kJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(EJ,{}):e.model.name===iC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(Rn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(HU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(Rn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(KU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function RJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},PJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",OJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},MJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function Qt(e){if(e)return IJ(e)}function IJ(e){for(var t in Qt.prototype)e[t]=Qt.prototype[t];return e}Qt.prototype.on=Qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};Qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};Qt.prototype.off=Qt.prototype.removeListener=Qt.prototype.removeAllListeners=Qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};MJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,OJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends Qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=YJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,ZJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class QJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends Qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends Qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[vee,Rte]=An(OA),[yee,wee]=vee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=_ee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(yee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(See(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function _ee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function See(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Cee=bee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const $ee="http://127.0.0.1:8080",Vi=rh($ee),kee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>{if(n)return Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}},[n]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},Ree=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await jj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(kee,{}),v.jsx(kJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Aee,Oee]=zd("Toast"),[jA,Tte]=An("Toast",[Oee]),[Mee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Mee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Iee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Nee,n),l=Aee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...Qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(_B,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Lee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Lee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(xn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Vee,Wee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Vee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(bB,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(jee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Fee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(Bee,y,K,{discrete:!0}):_p(zee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Zee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Gee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Gee}\``)}};const Xee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=zA,KA=Iee,YA=Uee,GA=Kee,XA=Yee,ZA=UA,qA=VA,ete=Jee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const tte=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const nte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function rte(){const{toasts:e}=Td();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Kj(),i=vH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Lj();n(y),y.isDesktop&&uF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;ote.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(Ree,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ste=typeof window>"u",rO=f.createContext(void 0),ate=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?dte():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},ute=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),fte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(BU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-iK_rIxV0.css b/py/iopaint/web_app/assets/index-iK_rIxV0.css new file mode 100644 index 0000000..a4f1f98 --- /dev/null +++ b/py/iopaint/web_app/assets/index-iK_rIxV0.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[500px\]{min-width:500px}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-kS3ik1bw.js b/py/iopaint/web_app/assets/index-kS3ik1bw.js new file mode 100644 index 0000000..6350972 --- /dev/null +++ b/py/iopaint/web_app/assets/index-kS3ik1bw.js @@ -0,0 +1,165 @@ +var Lv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Lv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Lv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Hf=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Lv(e,t,"access private method"),n);function $D(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Jc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function dm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y$={exports:{}},fm={},w$={exports:{}},it={};/** + * @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. + */var kd=Symbol.for("react.element"),RD=Symbol.for("react.portal"),kD=Symbol.for("react.fragment"),TD=Symbol.for("react.strict_mode"),PD=Symbol.for("react.profiler"),AD=Symbol.for("react.provider"),MD=Symbol.for("react.context"),OD=Symbol.for("react.forward_ref"),ND=Symbol.for("react.suspense"),DD=Symbol.for("react.memo"),ID=Symbol.for("react.lazy"),j_=Symbol.iterator;function LD(e){return e===null||typeof e!="object"?null:(e=j_&&e[j_]||e["@@iterator"],typeof e=="function"?e:null)}var x$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},b$=Object.assign,S$={};function yc(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}yc.prototype.isReactComponent={};yc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};yc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=yc.prototype;function nw(e,t,n){this.props=e,this.context=t,this.refs=S$,this.updater=n||x$}var rw=nw.prototype=new _$;rw.constructor=nw;b$(rw,yc.prototype);rw.isPureReactComponent=!0;var z_=Array.isArray,E$=Object.prototype.hasOwnProperty,ow={current:null},C$={key:!0,ref:!0,__self:!0,__source:!0};function $$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)E$.call(t,r)&&!C$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ce=K[se];if(0>>1;seo(We,H))Oeo(he,We)?(K[se]=he,K[Oe]=H,se=Oe):(K[se]=We,K[Ue]=H,se=Ue);else if(Oeo(he,H))K[se]=he,K[Oe]=H,se=Oe;else break e}}return Z}function o(K,Z){var H=K.sortIndex-Z.sortIndex;return H!==0?H:K.id-Z.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],f=[],m=1,p=null,g=3,y=!1,b=!1,S=!1,E=typeof setTimeout=="function"?setTimeout:null,_=typeof clearTimeout=="function"?clearTimeout:null,x=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function C(K){for(var Z=n(f);Z!==null;){if(Z.callback===null)r(f);else if(Z.startTime<=K)r(f),Z.sortIndex=Z.expirationTime,t(u,Z);else break;Z=n(f)}}function R(K){if(S=!1,C(K),!b)if(n(u)!==null)b=!0,N(P);else{var Z=n(f);Z!==null&&ie(R,Z.startTime-K)}}function P(K,Z){b=!1,S&&(S=!1,_(D),D=-1),y=!0;var H=g;try{for(C(Z),p=n(u);p!==null&&(!(p.expirationTime>Z)||K&&!q());){var se=p.callback;if(typeof se=="function"){p.callback=null,g=p.priorityLevel;var ce=se(p.expirationTime<=Z);Z=e.unstable_now(),typeof ce=="function"?p.callback=ce:p===n(u)&&r(u),C(Z)}else r(u);p=n(u)}if(p!==null)var Ve=!0;else{var Ue=n(f);Ue!==null&&ie(R,Ue.startTime-Z),Ve=!1}return Ve}finally{p=null,g=H,y=!1}}var M=!1,A=null,D=-1,U=5,W=-1;function q(){return!(e.unstable_now()-WK||125se?(K.sortIndex=H,t(f,K),n(u)===null&&K===n(f)&&(S?(_(D),D=-1):S=!0,ie(R,H-se))):(K.sortIndex=ce,t(u,K),b||y||(b=!0,N(P))),K},e.unstable_shouldYield=q,e.unstable_wrapCallback=function(K){var Z=g;return function(){var H=g;g=Z;try{return K.apply(this,arguments)}finally{g=H}}}})(P$);T$.exports=P$;var XD=T$.exports;/** + * @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. + */var A$=d,yr=XD;function ue(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),W0=Object.prototype.hasOwnProperty,ZD=/^[: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]*$/,U_={},V_={};function qD(e){return W0.call(V_,e)?!0:W0.call(U_,e)?!1:ZD.test(e)?V_[e]=!0:(U_[e]=!0,!1)}function QD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function JD(e,t,n,r){if(t===null||typeof t>"u"||QD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var bn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){bn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];bn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){bn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){bn[e]=new Un(e,2,!1,e,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(e){bn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){bn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){bn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){bn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){bn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var sw=/[\-:]([a-z])/g;function aw(e){return e[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(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(sw,aw);bn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});bn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){bn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function lw(e,t,n,r){var o=bn.hasOwnProperty(t)?bn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{zv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?vu(e):""}function e9(e){switch(e.tag){case 5:return vu(e.type);case 16:return vu("Lazy");case 13:return vu("Suspense");case 19:return vu("SuspenseList");case 0:case 2:case 15:return e=Bv(e.type,!1),e;case 11:return e=Bv(e.type.render,!1),e;case 1:return e=Bv(e.type,!0),e;default:return""}}function Y0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ml:return"Fragment";case pl:return"Portal";case H0:return"Profiler";case cw:return"StrictMode";case K0:return"Suspense";case G0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case N$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case uw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case dw:return t=e.displayName||null,t!==null?t:Y0(e.type)||"Memo";case Ji:t=e._payload,e=e._init;try{return Y0(e(t))}catch{}}return null}function t9(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Y0(t);case 8:return t===cw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Rs(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function I$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function n9(e){var t=I$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Yf(e){e._valueTracker||(e._valueTracker=n9(e))}function L$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=I$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function ap(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function X0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function H_(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Rs(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function F$(e,t){t=t.checked,t!=null&&lw(e,"checked",t,!1)}function Z0(e,t){F$(e,t);var n=Rs(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?q0(e,t.type,n):t.hasOwnProperty("defaultValue")&&q0(e,t.type,Rs(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function K_(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function q0(e,t,n){(t!=="number"||ap(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var yu=Array.isArray;function Rl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Xf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ju(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Eu={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},r9=["Webkit","ms","Moz","O"];Object.keys(Eu).forEach(function(e){r9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Eu[t]=Eu[e]})});function U$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Eu.hasOwnProperty(e)&&Eu[e]?(""+t).trim():t+"px"}function V$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=U$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var o9=zt({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 ey(e,t){if(t){if(o9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ue(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ue(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ue(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ue(62))}}function ty(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 ny=null;function fw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ry=null,kl=null,Tl=null;function X_(e){if(e=Ad(e)){if(typeof ry!="function")throw Error(ue(280));var t=e.stateNode;t&&(t=vm(t),ry(e.stateNode,e.type,t))}}function W$(e){kl?Tl?Tl.push(e):Tl=[e]:kl=e}function H$(){if(kl){var e=kl,t=Tl;if(Tl=kl=null,X_(e),t)for(e=0;e>>=0,e===0?32:31-(m9(e)/g9|0)|0}var Zf=64,qf=4194304;function wu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function dp(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=wu(l):(i&=s,i!==0&&(r=wu(i)))}else s=n&~o,s!==0?r=wu(s):i!==0&&(r=wu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Td(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-wo(t),e[t]=n}function x9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=$u),oE=" ",iE=!1;function dR(e,t){switch(e){case"keyup":return Y9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function fR(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var gl=!1;function Z9(e,t){switch(e){case"compositionend":return fR(t);case"keypress":return t.which!==32?null:(iE=!0,oE);case"textInput":return e=t.data,e===oE&&iE?null:e;default:return null}}function q9(e,t){if(gl)return e==="compositionend"||!xw&&dR(e,t)?(e=cR(),Oh=vw=us=null,gl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=cE(n)}}function gR(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?gR(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function vR(){for(var e=window,t=ap();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=ap(e.document)}return t}function bw(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function sI(e){var t=vR(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&gR(n.ownerDocument.documentElement,n)){if(r!==null&&bw(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=uE(n,i);var s=uE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,vl=null,cy=null,ku=null,uy=!1;function dE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;uy||vl==null||vl!==ap(r)||(r=vl,"selectionStart"in r&&bw(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}),ku&&Hu(ku,r)||(ku=r,r=pp(cy,"onSelect"),0xl||(e.current=gy[xl],gy[xl]=null,xl--)}function $t(e,t){xl++,gy[xl]=e.current,e.current=t}var ks={},Pn=Ns(ks),Jn=Ns(!1),Ra=ks;function Ql(e,t){var n=e.type.contextTypes;if(!n)return ks;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function gp(){At(Jn),At(Pn)}function yE(e,t,n){if(Pn.current!==ks)throw Error(ue(168));$t(Pn,t),$t(Jn,n)}function $R(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ue(108,t9(e)||"Unknown",o));return zt({},n,r)}function vp(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||ks,Ra=Pn.current,$t(Pn,e),$t(Jn,Jn.current),!0}function wE(e,t,n){var r=e.stateNode;if(!r)throw Error(ue(169));n?(e=$R(e,t,Ra),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Pn),$t(Pn,e)):At(Jn),$t(Jn,n)}var pi=null,ym=!1,t0=!1;function RR(e){pi===null?pi=[e]:pi.push(e)}function yI(e){ym=!0,RR(e)}function Ds(){if(!t0&&pi!==null){t0=!0;var e=0,t=xt;try{var n=pi;for(xt=1;e>=s,o-=s,mi=1<<32-wo(t)+o|n<D?(U=A,A=null):U=A.sibling;var W=g(_,A,C[D],R);if(W===null){A===null&&(A=U);break}e&&A&&W.alternate===null&&t(_,A),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W,A=U}if(D===C.length)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;DD?(U=A,A=null):U=A.sibling;var q=g(_,A,W.value,R);if(q===null){A===null&&(A=U);break}e&&A&&q.alternate===null&&t(_,A),x=i(q,x,D),M===null?P=q:M.sibling=q,M=q,A=U}if(W.done)return n(_,A),Dt&&ta(_,D),P;if(A===null){for(;!W.done;D++,W=C.next())W=p(_,W.value,R),W!==null&&(x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return Dt&&ta(_,D),P}for(A=r(_,A);!W.done;D++,W=C.next())W=y(A,_,D,W.value,R),W!==null&&(e&&W.alternate!==null&&A.delete(W.key===null?D:W.key),x=i(W,x,D),M===null?P=W:M.sibling=W,M=W);return e&&A.forEach(function(X){return t(_,X)}),Dt&&ta(_,D),P}function E(_,x,C,R){if(typeof C=="object"&&C!==null&&C.type===ml&&C.key===null&&(C=C.props.children),typeof C=="object"&&C!==null){switch(C.$$typeof){case Gf:e:{for(var P=C.key,M=x;M!==null;){if(M.key===P){if(P=C.type,P===ml){if(M.tag===7){n(_,M.sibling),x=o(M,C.props.children),x.return=_,_=x;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ji&&$E(P)===M.type){n(_,M.sibling),x=o(M,C.props),x.ref=iu(_,M,C),x.return=_,_=x;break e}n(_,M);break}else t(_,M);M=M.sibling}C.type===ml?(x=$a(C.props.children,_.mode,R,C.key),x.return=_,_=x):(R=Bh(C.type,C.key,C.props,null,_.mode,R),R.ref=iu(_,x,C),R.return=_,_=R)}return s(_);case pl:e:{for(M=C.key;x!==null;){if(x.key===M)if(x.tag===4&&x.stateNode.containerInfo===C.containerInfo&&x.stateNode.implementation===C.implementation){n(_,x.sibling),x=o(x,C.children||[]),x.return=_,_=x;break e}else{n(_,x);break}else t(_,x);x=x.sibling}x=c0(C,_.mode,R),x.return=_,_=x}return s(_);case Ji:return M=C._init,E(_,x,M(C._payload),R)}if(yu(C))return b(_,x,C,R);if(eu(C))return S(_,x,C,R);oh(_,C)}return typeof C=="string"&&C!==""||typeof C=="number"?(C=""+C,x!==null&&x.tag===6?(n(_,x.sibling),x=o(x,C),x.return=_,_=x):(n(_,x),x=l0(C,_.mode,R),x.return=_,_=x),s(_)):n(_,x)}return E}var ec=DR(!0),IR=DR(!1),Md={},Ko=Ns(Md),Xu=Ns(Md),Zu=Ns(Md);function fa(e){if(e===Md)throw Error(ue(174));return e}function Pw(e,t){switch($t(Zu,t),$t(Xu,e),$t(Ko,Md),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:J0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=J0(t,e)}At(Ko),$t(Ko,t)}function tc(){At(Ko),At(Xu),At(Zu)}function LR(e){fa(Zu.current);var t=fa(Ko.current),n=J0(t,e.type);t!==n&&($t(Xu,e),$t(Ko,n))}function Aw(e){Xu.current===e&&(At(Ko),At(Xu))}var Lt=Ns(0);function _p(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var n0=[];function Mw(){for(var e=0;en?n:4,e(!0);var r=r0.transition;r0.transition={};try{e(!1),t()}finally{xt=n,r0.transition=r}}function JR(){return Yr().memoizedState}function SI(e,t,n){var r=Ss(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ek(e))tk(t,n);else if(n=AR(e,t,n,r),n!==null){var o=jn();xo(n,e,r,o),nk(n,t,r)}}function _I(e,t,n){var r=Ss(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ek(e))tk(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,So(l,s)){var u=t.interleaved;u===null?(o.next=o,kw(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=AR(e,t,o,r),n!==null&&(o=jn(),xo(n,e,r,o),nk(n,t,r))}}function ek(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function tk(e,t){Tu=Ep=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function nk(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,pw(e,n)}}var Cp={readContext:Gr,useCallback:$n,useContext:$n,useEffect:$n,useImperativeHandle:$n,useInsertionEffect:$n,useLayoutEffect:$n,useMemo:$n,useReducer:$n,useRef:$n,useState:$n,useDebugValue:$n,useDeferredValue:$n,useTransition:$n,useMutableSource:$n,useSyncExternalStore:$n,useId:$n,unstable_isNewReconciler:!1},EI={readContext:Gr,useCallback:function(e,t){return Po().memoizedState=[e,t===void 0?null:t],e},useContext:Gr,useEffect:kE,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Lh(4194308,4,YR.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Lh(4194308,4,e,t)},useInsertionEffect:function(e,t){return Lh(4,2,e,t)},useMemo:function(e,t){var n=Po();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Po();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=SI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=Po();return e={current:e},t.memoizedState=e},useState:RE,useDebugValue:Lw,useDeferredValue:function(e){return Po().memoizedState=e},useTransition:function(){var e=RE(!1),t=e[0];return e=bI.bind(null,e[1]),Po().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=Po();if(Dt){if(n===void 0)throw Error(ue(407));n=n()}else{if(n=t(),dn===null)throw Error(ue(349));Ta&30||zR(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,kE(UR.bind(null,r,i,e),[e]),r.flags|=2048,Ju(9,BR.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=Po(),t=dn.identifierPrefix;if(Dt){var n=gi,r=mi;n=(r&~(1<<32-wo(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=qu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Io]=t,e[Yu]=r,dk(e,t,!1,!1),t.stateNode=e;e:{switch(s=ty(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;orc&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304)}else{if(!r)if(e=_p(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),su(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return Rn(t),null}else 2*Xt()-i.renderingStartTime>rc&&n!==1073741824&&(t.flags|=128,r=!0,su(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):(Rn(t),null);case 22:case 23:return Vw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&(Rn(t),t.subtreeFlags&6&&(t.flags|=8192)):Rn(t),null;case 24:return null;case 25:return null}throw Error(ue(156,t.tag))}function MI(e,t){switch(_w(t),t.tag){case 1:return er(t.type)&&gp(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return tc(),At(Jn),At(Pn),Mw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Aw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ue(340));Jl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return tc(),null;case 10:return Rw(t.type._context),null;case 22:case 23:return Vw(),null;case 24:return null;default:return null}}var sh=!1,Tn=!1,OI=typeof WeakSet=="function"?WeakSet:Set,_e=null;function El(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function ky(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var LE=!1;function NI(e,t){if(dy=fp,e=vR(),bw(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,f=0,m=0,p=e,g=null;t:for(;;){for(var y;p!==n||o!==0&&p.nodeType!==3||(l=s+o),p!==i||r!==0&&p.nodeType!==3||(u=s+r),p.nodeType===3&&(s+=p.nodeValue.length),(y=p.firstChild)!==null;)g=p,p=y;for(;;){if(p===e)break t;if(g===n&&++f===o&&(l=s),g===i&&++m===r&&(u=s),(y=p.nextSibling)!==null)break;p=g,g=p.parentNode}p=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(fy={focusedElem:e,selectionRange:n},fp=!1,_e=t;_e!==null;)if(t=_e,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,_e=e;else for(;_e!==null;){t=_e;try{var b=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(b!==null){var S=b.memoizedProps,E=b.memoizedState,_=t.stateNode,x=_.getSnapshotBeforeUpdate(t.elementType===t.type?S:io(t.type,S),E);_.__reactInternalSnapshotBeforeUpdate=x}break;case 3:var C=t.stateNode.containerInfo;C.nodeType===1?C.textContent="":C.nodeType===9&&C.documentElement&&C.removeChild(C.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ue(163))}}catch(R){Wt(t,t.return,R)}if(e=t.sibling,e!==null){e.return=t.return,_e=e;break}_e=t.return}return b=LE,LE=!1,b}function Pu(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&ky(t,n,i)}o=o.next}while(o!==r)}}function bm(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Ty(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pk(e){var t=e.alternate;t!==null&&(e.alternate=null,pk(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Io],delete t[Yu],delete t[my],delete t[gI],delete t[vI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function mk(e){return e.tag===5||e.tag===3||e.tag===4}function FE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||mk(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Py(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=mp));else if(r!==4&&(e=e.child,e!==null))for(Py(e,t,n),e=e.sibling;e!==null;)Py(e,t,n),e=e.sibling}function Ay(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ay(e,t,n),e=e.sibling;e!==null;)Ay(e,t,n),e=e.sibling}var mn=null,lo=!1;function Ki(e,t,n){for(n=n.child;n!==null;)gk(e,t,n),n=n.sibling}function gk(e,t,n){if(Ho&&typeof Ho.onCommitFiberUnmount=="function")try{Ho.onCommitFiberUnmount(hm,n)}catch{}switch(n.tag){case 5:Tn||El(n,t);case 6:var r=mn,o=lo;mn=null,Ki(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e0(e.parentNode,n):e.nodeType===1&&e0(e,n),Vu(e)):e0(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,Ki(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Tn&&(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||i&4)&&ky(n,t,s),o=o.next}while(o!==r)}Ki(e,t,n);break;case 1:if(!Tn&&(El(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}Ki(e,t,n);break;case 21:Ki(e,t,n);break;case 22:n.mode&1?(Tn=(r=Tn)||n.memoizedState!==null,Ki(e,t,n),Tn=r):Ki(e,t,n);break;default:Ki(e,t,n)}}function jE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new OI),t.forEach(function(r){var o=VI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*II(r/1960))-r,10e?16:e,ds===null)var r=!1;else{if(e=ds,ds=null,kp=0,dt&6)throw Error(ue(331));var o=dt;for(dt|=4,_e=e.current;_e!==null;){var i=_e,s=i.child;if(_e.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-Bw?Ca(e,0):zw|=n),tr(e,t)}function Ek(e,t){t===0&&(e.mode&1?(t=qf,qf<<=1,!(qf&130023424)&&(qf=4194304)):t=1);var n=jn();e=_i(e,t),e!==null&&(Td(e,t,n),tr(e,n))}function UI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Ek(e,n)}function VI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ue(314))}r!==null&&r.delete(t),Ek(e,n)}var Ck;Ck=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,PI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kR(t,wp,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Fh(e,t),e=t.pendingProps;var o=Ql(t,Pn.current);Al(t,n),o=Nw(null,t,r,e,o,n);var i=Dw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,vp(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,Tw(t),o.updater=wm,t.stateNode=o,o._reactInternals=t,by(t,r,e,n),t=Ey(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&Sw(t),In(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Fh(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=HI(r),e=io(r,e),o){case 0:t=_y(null,t,r,e,n);break e;case 1:t=NE(null,t,r,e,n);break e;case 11:t=ME(null,t,r,e,n);break e;case 14:t=OE(null,t,r,io(r.type,e),n);break e}throw Error(ue(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),_y(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),NE(e,t,r,o,n);case 3:e:{if(lk(t),e===null)throw Error(ue(387));r=t.pendingProps,i=t.memoizedState,o=i.element,MR(e,t),Sp(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=nc(Error(ue(423)),t),t=DE(e,t,r,n,o);break e}else if(r!==o){o=nc(Error(ue(424)),t),t=DE(e,t,r,n,o);break e}else for(mr=ws(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,ho=null,n=IR(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Jl(),r===o){t=Ei(e,t,n);break e}In(e,t,r,n)}t=t.child}return t;case 5:return LR(t),e===null&&yy(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,hy(r,o)?s=null:i!==null&&hy(r,i)&&(t.flags|=32),ak(e,t),In(e,t,s,n),t.child;case 6:return e===null&&yy(t),null;case 13:return ck(e,t,n);case 4:return Pw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=ec(t,null,r,n):In(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),ME(e,t,r,o,n);case 7:return In(e,t,t.pendingProps,n),t.child;case 8:return In(e,t,t.pendingProps.children,n),t.child;case 12:return In(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(xp,r._currentValue),r._currentValue=s,i!==null)if(So(i.value,s)){if(i.children===o.children&&!Jn.current){t=Ei(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=wi(-1,n&-n),u.tag=2;var f=i.updateQueue;if(f!==null){f=f.shared;var m=f.pending;m===null?u.next=u:(u.next=m.next,m.next=u),f.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),wy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ue(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),wy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}In(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Al(t,n),o=Gr(o),r=r(o),t.flags|=1,In(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),OE(e,t,r,o,n);case 15:return ik(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Fh(e,t),t.tag=1,er(r)?(e=!0,vp(t)):e=!1,Al(t,n),NR(t,r,o),by(t,r,o,n),Ey(null,t,r,!0,e,n);case 19:return uk(e,t,n);case 22:return sk(e,t,n)}throw Error(ue(156,t.tag))};function $k(e,t){return Q$(e,t)}function WI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new WI(e,t,n,r)}function Hw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function HI(e){if(typeof e=="function")return Hw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===uw)return 11;if(e===dw)return 14}return 2}function _s(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Bh(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Hw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ml:return $a(n.children,o,i,t);case cw:s=8,o|=8;break;case H0:return e=Ur(12,n,t,o|2),e.elementType=H0,e.lanes=i,e;case K0:return e=Ur(13,n,t,o),e.elementType=K0,e.lanes=i,e;case G0:return e=Ur(19,n,t,o),e.elementType=G0,e.lanes=i,e;case D$:return _m(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case N$:s=9;break e;case uw:s=11;break e;case dw:s=14;break e;case Ji:s=16,r=null;break e}throw Error(ue(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function $a(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function _m(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=D$,e.lanes=n,e.stateNode={isHidden:!1},e}function l0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function c0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function KI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Vv(0),this.expirationTimes=Vv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Vv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Kw(e,t,n,r,o,i,s,l,u){return e=new KI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tw(i),e}function GI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Pk)}catch(e){console.error(e)}}Pk(),k$.exports=br;var Is=k$.exports;const QI=dm(Is);var GE=Is;V0.createRoot=GE.createRoot,V0.hydrateRoot=GE.hydrateRoot;var Od=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},oc=typeof window>"u"||"Deno"in window;function Lr(){}function JI(e,t){return typeof e=="function"?e(t):e}function Iy(e){return typeof e=="number"&&e>=0&&e!==1/0}function Ak(e,t){return Math.max(e+(t||0)-Date.now(),0)}function YE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Zw(s,t.options))return!1}else if(!nd(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function XE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(td(t.options.mutationKey)!==td(i))return!1}else if(!nd(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Zw(e,t){return((t==null?void 0:t.queryKeyHashFn)||td)(e)}function td(e){return JSON.stringify(e,(t,n)=>Fy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function nd(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!nd(e[n],t[n])):!1}function Mk(e,t){if(e===t)return e;const n=ZE(e)&&ZE(t);if(n||Fy(e)&&Fy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!qE(n)||!n.hasOwnProperty("isPrototypeOf"))}function qE(e){return Object.prototype.toString.call(e)==="[object Object]"}function Ok(e){return new Promise(t=>{setTimeout(t,e)})}function QE(e){Ok(0).then(e)}function jy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?Mk(e,t):t}function eL(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function tL(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ga,rs,Il,c$,nL=(c$=class extends Od{constructor(){super();Te(this,ga,void 0);Te(this,rs,void 0);Te(this,Il,void 0);ye(this,Il,t=>{if(!oc&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,rs)||this.setEventListener(z(this,Il))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,rs))==null||t.call(this),ye(this,rs,void 0))}setEventListener(t){var n;ye(this,Il,t),(n=z(this,rs))==null||n.call(this),ye(this,rs,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ga)!==t&&(ye(this,ga,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ga)=="boolean"?z(this,ga):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ga=new WeakMap,rs=new WeakMap,Il=new WeakMap,c$),Ap=new nL,Ll,os,Fl,u$,rL=(u$=class extends Od{constructor(){super();Te(this,Ll,!0);Te(this,os,void 0);Te(this,Fl,void 0);ye(this,Fl,t=>{if(!oc&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,os)||this.setEventListener(z(this,Fl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,os))==null||t.call(this),ye(this,os,void 0))}setEventListener(t){var n;ye(this,Fl,t),(n=z(this,os))==null||n.call(this),ye(this,os,t(this.setOnline.bind(this)))}setOnline(t){z(this,Ll)!==t&&(ye(this,Ll,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Ll)}},Ll=new WeakMap,os=new WeakMap,Fl=new WeakMap,u$),Mp=new rL;function oL(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??"online")==="online"?Mp.isOnline():!0}var Nk=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function u0(e){return e instanceof Nk}function Dk(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((E,_)=>{i=E,s=_}),u=E=>{var _;r||(y(new Nk(E)),(_=e.abort)==null||_.call(e))},f=()=>{t=!0},m=()=>{t=!1},p=()=>!Ap.isFocused()||e.networkMode!=="always"&&!Mp.isOnline(),g=E=>{var _;r||(r=!0,(_=e.onSuccess)==null||_.call(e,E),o==null||o(),i(E))},y=E=>{var _;r||(r=!0,(_=e.onError)==null||_.call(e,E),o==null||o(),s(E))},b=()=>new Promise(E=>{var _;o=x=>{const C=r||!p();return C&&E(x),C},(_=e.onPause)==null||_.call(e)}).then(()=>{var E;o=void 0,r||(E=e.onContinue)==null||E.call(e)}),S=()=>{if(r)return;let E;try{E=e.fn()}catch(_){E=Promise.reject(_)}Promise.resolve(E).then(g).catch(_=>{var M;if(r)return;const x=e.retry??(oc?0:3),C=e.retryDelay??oL,R=typeof C=="function"?C(n,_):C,P=x===!0||typeof x=="number"&&n{if(p())return b()}).then(()=>{t?y(_):S()})})};return km(e.networkMode)?S():b().then(S),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:f,continueRetry:m}}function iL(){let e=[],t=0,n=m=>{m()},r=m=>{m()};const o=m=>{let p;t++;try{p=m()}finally{t--,t||l()}return p},i=m=>{t?e.push(m):QE(()=>{n(m)})},s=m=>(...p)=>{i(()=>{m(...p)})},l=()=>{const m=e;e=[],m.length&&QE(()=>{r(()=>{m.forEach(p=>{n(p)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:m=>{n=m},setBatchNotifyFunction:m=>{r=m}}}var vn=iL(),va,d$,Ik=(d$=class{constructor(){Te(this,va,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Iy(this.gcTime)&&ye(this,va,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(oc?1/0:5*60*1e3))}clearGcTimeout(){z(this,va)&&(clearTimeout(z(this,va)),ye(this,va,void 0))}},va=new WeakMap,d$),jl,zl,Nr,is,Dr,cn,vd,ya,Bl,Uh,ao,di,f$,sL=(f$=class extends Ik{constructor(t){super();Te(this,Bl);Te(this,ao);Te(this,jl,void 0);Te(this,zl,void 0);Te(this,Nr,void 0);Te(this,is,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,vd,void 0);Te(this,ya,void 0);ye(this,ya,!1),ye(this,vd,t.defaultOptions),tt(this,Bl,Uh).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,jl,t.state||aL(this.options)),this.state=z(this,jl),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=jy(this.state.data,t,this.options);return tt(this,ao,di).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,di).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,is);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,jl))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!Ak(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,ya)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,di).call(this,{type:"invalidate"})}fetch(t,n){var f,m,p,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,is))return(f=z(this,Dr))==null||f.continueRetry(),z(this,is)}if(t&&tt(this,Bl,Uh).call(this,t),!this.options.queryFn){const y=z(this,cn).find(b=>b.options.queryFn);y&&tt(this,Bl,Uh).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,ya,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,ya,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(m=this.options.behavior)==null||m.onFetch(l,this),ye(this,zl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((p=l.fetchOptions)==null?void 0:p.meta))&&tt(this,ao,di).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var b,S,E,_;u0(y)&&y.silent||tt(this,ao,di).call(this,{type:"error",error:y}),u0(y)||((S=(b=z(this,Nr).config).onError)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,Dk({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var b,S,E,_;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(S=(b=z(this,Nr).config).onSuccess)==null||S.call(b,y,this),(_=(E=z(this,Nr).config).onSettled)==null||_.call(E,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,b)=>{tt(this,ao,di).call(this,{type:"failed",failureCount:y,error:b})},onPause:()=>{tt(this,ao,di).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,di).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,is,z(this,Dr).promise),z(this,is)}},jl=new WeakMap,zl=new WeakMap,Nr=new WeakMap,is=new WeakMap,Dr=new WeakMap,cn=new WeakMap,vd=new WeakMap,ya=new WeakMap,Bl=new WeakSet,Uh=function(t){this.options={...z(this,vd),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,di=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:km(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return u0(o)&&o.revert&&z(this,zl)?{...z(this,zl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),vn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},f$);function aL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Mo,h$,lL=(h$=class extends Od{constructor(t={}){super();Te(this,Mo,void 0);this.config=t,ye(this,Mo,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Zw(o,n);let s=this.get(i);return s||(s=new sL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Mo).has(t.queryHash)||(z(this,Mo).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Mo).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Mo).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){vn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Mo).get(t)}getAll(){return[...z(this,Mo).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>YE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>YE(t,r)):n}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){vn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){vn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Mo=new WeakMap,h$),Oo,yd,dr,Ul,No,qi,p$,cL=(p$=class extends Ik{constructor(t){super();Te(this,No);Te(this,Oo,void 0);Te(this,yd,void 0);Te(this,dr,void 0);Te(this,Ul,void 0);this.mutationId=t.mutationId,ye(this,yd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,Oo,[]),this.state=t.state||uL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,yd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,Oo).includes(t)||(z(this,Oo).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,Oo,z(this,Oo).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,Oo).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Ul))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A;const n=()=>(ye(this,Ul,Dk({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(D,U)=>{tt(this,No,qi).call(this,{type:"failed",failureCount:D,error:U})},onPause:()=>{tt(this,No,qi).call(this,{type:"pause"})},onContinue:()=>{tt(this,No,qi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Ul).promise),r=this.state.status==="pending";try{if(!r){tt(this,No,qi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const U=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));U!==this.state.context&&tt(this,No,qi).call(this,{type:"pending",context:U,variables:t})}const D=await n();return await((f=(u=z(this,dr).config).onSuccess)==null?void 0:f.call(u,D,t,this.state.context,this)),await((p=(m=this.options).onSuccess)==null?void 0:p.call(m,D,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,D,null,this.state.variables,this.state.context,this)),await((S=(b=this.options).onSettled)==null?void 0:S.call(b,D,null,t,this.state.context)),tt(this,No,qi).call(this,{type:"success",data:D}),D}catch(D){try{throw await((_=(E=z(this,dr).config).onError)==null?void 0:_.call(E,D,t,this.state.context,this)),await((C=(x=this.options).onError)==null?void 0:C.call(x,D,t,this.state.context)),await((P=(R=z(this,dr).config).onSettled)==null?void 0:P.call(R,void 0,D,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,D,t,this.state.context)),D}finally{tt(this,No,qi).call(this,{type:"error",error:D})}}}},Oo=new WeakMap,yd=new WeakMap,dr=new WeakMap,Ul=new WeakMap,No=new WeakSet,qi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!km(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),vn.batch(()=>{z(this,Oo).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function uL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,wd,wa,m$,dL=(m$=class extends Od{constructor(t={}){super();Te(this,Ir,void 0);Te(this,wd,void 0);Te(this,wa,void 0);this.config=t,ye(this,Ir,[]),ye(this,wd,0)}build(t,n,r){const o=new cL({mutationCache:this,mutationId:++Hf(this,wd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){vn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>XE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>XE(t,n))}notify(t){vn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,wa,(z(this,wa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return vn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,wa,void 0)})),z(this,wa)}},Ir=new WeakMap,wd=new WeakMap,wa=new WeakMap,m$);function fL(e){return{onFetch:(t,n)=>{const r=async()=>{var b,S,E,_,x;const o=t.options,i=(E=(S=(b=t.fetchOptions)==null?void 0:b.meta)==null?void 0:S.fetchMore)==null?void 0:E.direction,s=((_=t.state.data)==null?void 0:_.pages)||[],l=((x=t.state.data)==null?void 0:x.pageParams)||[],u={pages:[],pageParams:[]};let f=!1;const m=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>(t.signal.aborted?f=!0:t.signal.addEventListener("abort",()=>{f=!0}),t.signal)})},p=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(C,R,P)=>{if(f)return Promise.reject();if(R==null&&C.pages.length)return Promise.resolve(C);const M={queryKey:t.queryKey,pageParam:R,direction:P?"backward":"forward",meta:t.options.meta};m(M);const A=await p(M),{maxPages:D}=t.options,U=P?tL:eL;return{pages:U(C.pages,A,D),pageParams:U(C.pageParams,R,D)}};let y;if(i&&s.length){const C=i==="backward",R=C?hL:JE,P={pages:s,pageParams:l},M=R(o,P);y=await g(P,M,C)}else{y=await g(u,l[0]??o.initialPageParam);const C=e??s.length;for(let R=1;R{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function JE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function hL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,ss,as,Vl,Wl,ls,Hl,Kl,g$,pL=(g$=class{constructor(e={}){Te(this,nn,void 0);Te(this,ss,void 0);Te(this,as,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ls,void 0);Te(this,Hl,void 0);Te(this,Kl,void 0);ye(this,nn,e.queryCache||new lL),ye(this,ss,e.mutationCache||new dL),ye(this,as,e.defaultOptions||{}),ye(this,Vl,new Map),ye(this,Wl,new Map),ye(this,ls,0)}mount(){Hf(this,ls)._++,z(this,ls)===1&&(ye(this,Hl,Ap.subscribe(()=>{Ap.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,Kl,Mp.subscribe(()=>{Mp.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Hf(this,ls)._--,z(this,ls)===0&&((e=z(this,Hl))==null||e.call(this),ye(this,Hl,void 0),(t=z(this,Kl))==null||t.call(this),ye(this,Kl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,ss).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=JI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return vn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);vn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return vn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=vn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return vn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=vn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=fL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,ss).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,ss)}getDefaultOptions(){return z(this,as)}setDefaultOptions(e){ye(this,as,e)}setQueryDefaults(e,t){z(this,Vl).set(td(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Vl).values()];let n={};return t.forEach(r=>{nd(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Wl).set(td(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Wl).values()];let n={};return t.forEach(r=>{nd(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,as).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Zw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,as).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,ss).clear()}},nn=new WeakMap,ss=new WeakMap,as=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ls=new WeakMap,Hl=new WeakMap,Kl=new WeakMap,g$),Xn,Ct,Gl,kn,xa,Yl,Do,xd,Xl,Zl,ba,Sa,cs,_a,Ea,bu,bd,zy,Sd,By,_d,Uy,Ed,Vy,Cd,Wy,$d,Hy,Rd,Ky,um,Lk,v$,mL=(v$=class extends Od{constructor(t,n){super();Te(this,Ea);Te(this,bd);Te(this,Sd);Te(this,_d);Te(this,Ed);Te(this,Cd);Te(this,$d);Te(this,Rd);Te(this,um);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Gl,void 0);Te(this,kn,void 0);Te(this,xa,void 0);Te(this,Yl,void 0);Te(this,Do,void 0);Te(this,xd,void 0);Te(this,Xl,void 0);Te(this,Zl,void 0);Te(this,ba,void 0);Te(this,Sa,void 0);Te(this,cs,void 0);Te(this,_a,void 0);ye(this,Ct,void 0),ye(this,Gl,void 0),ye(this,kn,void 0),ye(this,_a,new Set),ye(this,Xn,t),this.options=n,ye(this,Do,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),eC(z(this,Ct),this.options)?tt(this,Ea,bu).call(this):this.updateResult(),tt(this,Ed,Vy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,Cd,Wy).call(this),tt(this,$d,Hy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ly(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,Rd,Ky).call(this);const i=this.hasListeners();i&&tC(z(this,Ct),o,this.options,r)&&tt(this,Ea,bu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,bd,zy).call(this);const s=tt(this,Sd,By).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,cs))&&tt(this,_d,Uy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return vL(this,r)&&(ye(this,kn,r),ye(this,Yl,this.options),ye(this,xa,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,_a).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,Ea,bu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,xa),l=z(this,Yl),f=t!==r?t.state:z(this,Gl),{state:m}=t;let{error:p,errorUpdatedAt:g,fetchStatus:y,status:b}=m,S=!1,E;if(n._optimisticResults){const A=this.hasListeners(),D=!A&&eC(t,n),U=A&&tC(t,r,n,o);(D||U)&&(y=km(t.options.networkMode)?"fetching":"paused",m.dataUpdatedAt||(b="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof m.data<"u")if(i&&m.data===(s==null?void 0:s.data)&&n.select===z(this,xd))E=z(this,Xl);else try{ye(this,xd,n.select),E=n.select(m.data),E=jy(i==null?void 0:i.data,E,n),ye(this,Xl,E),ye(this,Do,null)}catch(A){ye(this,Do,A)}else E=m.data;if(typeof n.placeholderData<"u"&&typeof E>"u"&&b==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Zl))==null?void 0:M.state.data,z(this,Zl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Do,null)}catch(D){ye(this,Do,D)}typeof A<"u"&&(b="success",E=jy(i==null?void 0:i.data,A,n),S=!0)}z(this,Do)&&(p=z(this,Do),E=z(this,Xl),g=Date.now(),b="error");const _=y==="fetching",x=b==="pending",C=b==="error",R=x&&_;return{status:b,fetchStatus:y,isPending:x,isSuccess:b==="success",isError:C,isInitialLoading:R,isLoading:R,data:E,dataUpdatedAt:m.dataUpdatedAt,error:p,errorUpdatedAt:g,failureCount:m.fetchFailureCount,failureReason:m.fetchFailureReason,errorUpdateCount:m.errorUpdateCount,isFetched:m.dataUpdateCount>0||m.errorUpdateCount>0,isFetchedAfterMount:m.dataUpdateCount>f.dataUpdateCount||m.errorUpdateCount>f.errorUpdateCount,isFetching:_,isRefetching:_&&!x,isLoadingError:C&&m.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:S,isRefetchError:C&&m.dataUpdatedAt!==0,isStale:qw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,xa,z(this,Ct).state),ye(this,Yl,this.options),z(this,xa).data!==void 0&&ye(this,Zl,z(this,Ct)),Ly(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,_a).size)return!0;const u=new Set(l??z(this,_a));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(f=>{const m=f;return z(this,kn)[m]!==n[m]&&u.has(m)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,um,Lk).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,Ed,Vy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Gl=new WeakMap,kn=new WeakMap,xa=new WeakMap,Yl=new WeakMap,Do=new WeakMap,xd=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,ba=new WeakMap,Sa=new WeakMap,cs=new WeakMap,_a=new WeakMap,Ea=new WeakSet,bu=function(t){tt(this,Rd,Ky).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},bd=new WeakSet,zy=function(){if(tt(this,Cd,Wy).call(this),oc||z(this,kn).isStale||!Iy(this.options.staleTime))return;const n=Ak(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ba,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},Sd=new WeakSet,By=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},_d=new WeakSet,Uy=function(t){tt(this,$d,Hy).call(this),ye(this,cs,t),!(oc||this.options.enabled===!1||!Iy(z(this,cs))||z(this,cs)===0)&&ye(this,Sa,setInterval(()=>{(this.options.refetchIntervalInBackground||Ap.isFocused())&&tt(this,Ea,bu).call(this)},z(this,cs)))},Ed=new WeakSet,Vy=function(){tt(this,bd,zy).call(this),tt(this,_d,Uy).call(this,tt(this,Sd,By).call(this))},Cd=new WeakSet,Wy=function(){z(this,ba)&&(clearTimeout(z(this,ba)),ye(this,ba,void 0))},$d=new WeakSet,Hy=function(){z(this,Sa)&&(clearInterval(z(this,Sa)),ye(this,Sa,void 0))},Rd=new WeakSet,Ky=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Gl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},um=new WeakSet,Lk=function(t){vn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},v$);function gL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function eC(e,t){return gL(e,t)||e.state.dataUpdatedAt>0&&Gy(e,t,t.refetchOnMount)}function Gy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&qw(e,t)}return!1}function tC(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&qw(e,n)}function qw(e,t){return e.isStaleByTime(t.staleTime)}function vL(e,t){return!Ly(e.getCurrentResult(),t)}var Fk=d.createContext(void 0),yL=e=>{const t=d.useContext(Fk);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wL=({client:e,children:t})=>(d.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),d.createElement(Fk.Provider,{value:e},t)),jk=d.createContext(!1),xL=()=>d.useContext(jk);jk.Provider;function bL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var SL=d.createContext(bL()),_L=()=>d.useContext(SL);function EL(e,t){return typeof e=="function"?e(...t):!!e}var CL=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},$L=e=>{d.useEffect(()=>{e.clearReset()},[e])},RL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&EL(n,[e.error,r]),kL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},TL=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,PL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function AL(e,t,n){const r=yL(n),o=xL(),i=_L(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",kL(s),CL(s,i),$L(i);const[l]=d.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(d.useSyncExternalStore(d.useCallback(f=>{const m=o?()=>{}:l.subscribe(vn.batchCalls(f));return l.updateResult(),m},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),d.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),TL(s,u))throw l.setOptions(s,{listeners:!1}),PL(s,l,i);if(RL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function ML(e,t){return AL(e,mL,t)}var Ao=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(Ao||{}),Es=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(Es||{}),Ou=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))(Ou||{}),Qw=(e=>(e.ddim="ddim",e.plms="plms",e))(Qw||{}),Jw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(Jw||{}),Ln=(e=>(e.x="x",e.y="y",e.xy="xy",e))(Ln||{}),Ol=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(Ol||{});function zk(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const nC=/^\[(.+)\]$/;function NL(e){if(nC.test(e)){const t=nC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function DL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return LL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Yy(s,r,i,t)}),r}function Yy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:rC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(IL(o)){Yy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Yy(s,rC(t,i),n,r)})})}function rC(e,t){let n=e;return t.split(ex).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function IL(e){return e.isThemeGetter}function LL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function FL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const Vk="!";function jL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,f=0,m;for(let S=0;Sf?m-f:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:b}}}function zL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function BL(e){return{cache:FL(e.cacheSize),splitModifiers:jL(e),...OL(e)}}const UL=/\s+/;function VL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(UL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:f,maybePostfixModifierPosition:m}=n(s);let p=r(m?f.substring(0,m):f),g=!!m;if(!p){if(!m)return{isTailwindClass:!1,originalClassName:s};if(p=r(f),!p)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=zL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+Vk:y,classGroupId:p,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:f}=s,m=l+u;return i.has(m)?!1:(i.add(m),o(u,f).forEach(p=>i.add(l+p)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function WL(){let e=0,t,n,r="";for(;ep(m),e());return n=BL(f),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const f=r(u);if(f)return f;const m=VL(u,n);return o(u,m),m}return function(){return i(WL.apply(null,arguments))}}function kt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const Hk=/^\[(?:([a-z-]+):)?(.+)\]$/i,KL=/^\d+\/\d+$/,GL=new Set(["px","full","screen"]),YL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,XL=/\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$/,ZL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,qL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ha(e)||GL.has(e)||KL.test(e)}function Gi(e){return bc(e,"length",iF)}function ha(e){return!!e&&!Number.isNaN(Number(e))}function ch(e){return bc(e,"number",ha)}function lu(e){return!!e&&Number.isInteger(Number(e))}function QL(e){return e.endsWith("%")&&ha(e.slice(0,-1))}function Je(e){return Hk.test(e)}function Yi(e){return YL.test(e)}const JL=new Set(["length","size","percentage"]);function eF(e){return bc(e,JL,Kk)}function tF(e){return bc(e,"position",Kk)}const nF=new Set(["image","url"]);function rF(e){return bc(e,nF,aF)}function oF(e){return bc(e,"",sF)}function cu(){return!0}function bc(e,t,n){const r=Hk.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function iF(e){return XL.test(e)}function Kk(){return!1}function sF(e){return ZL.test(e)}function aF(e){return qL.test(e)}function lF(){const e=kt("colors"),t=kt("spacing"),n=kt("blur"),r=kt("brightness"),o=kt("borderColor"),i=kt("borderRadius"),s=kt("borderSpacing"),l=kt("borderWidth"),u=kt("contrast"),f=kt("grayscale"),m=kt("hueRotate"),p=kt("invert"),g=kt("gap"),y=kt("gradientColorStops"),b=kt("gradientColorStopPositions"),S=kt("inset"),E=kt("margin"),_=kt("opacity"),x=kt("padding"),C=kt("saturate"),R=kt("scale"),P=kt("sepia"),M=kt("skew"),A=kt("space"),D=kt("translate"),U=()=>["auto","contain","none"],W=()=>["auto","hidden","clip","visible","scroll"],q=()=>["auto",Je,t],X=()=>[Je,t],ae=()=>["",oo,Gi],V=()=>["auto",ha,Je],F=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],N=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Z=()=>["","0",Je],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],se=()=>[ha,ch],ce=()=>[ha,Je];return{cacheSize:500,separator:":",theme:{colors:[cu],spacing:[oo,Gi],blur:["none","",Yi,Je],brightness:se(),borderColor:[e],borderRadius:["none","","full",Yi,Je],borderSpacing:X(),borderWidth:ae(),contrast:se(),grayscale:Z(),hueRotate:ce(),invert:Z(),gap:X(),gradientColorStops:[e],gradientColorStopPositions:[QL,Gi],inset:q(),margin:q(),opacity:se(),padding:X(),saturate:se(),scale:se(),sepia:Z(),skew:ce(),space:X(),translate:X()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Yi]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...F(),Je]}],overflow:[{overflow:W()}],"overflow-x":[{"overflow-x":W()}],"overflow-y":[{"overflow-y":W()}],overscroll:[{overscroll:U()}],"overscroll-x":[{"overscroll-x":U()}],"overscroll-y":[{"overscroll-y":U()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[S]}],"inset-x":[{"inset-x":[S]}],"inset-y":[{"inset-y":[S]}],start:[{start:[S]}],end:[{end:[S]}],top:[{top:[S]}],right:[{right:[S]}],bottom:[{bottom:[S]}],left:[{left:[S]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",lu,Je]}],basis:[{basis:q()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Z()}],shrink:[{shrink:Z()}],order:[{order:["first","last","none",lu,Je]}],"grid-cols":[{"grid-cols":[cu]}],"col-start-end":[{col:["auto",{span:["full",lu,Je]},Je]}],"col-start":[{"col-start":V()}],"col-end":[{"col-end":V()}],"grid-rows":[{"grid-rows":[cu]}],"row-start-end":[{row:["auto",{span:[lu,Je]},Je]}],"row-start":[{"row-start":V()}],"row-end":[{"row-end":V()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[E]}],mx:[{mx:[E]}],my:[{my:[E]}],ms:[{ms:[E]}],me:[{me:[E]}],mt:[{mt:[E]}],mr:[{mr:[E]}],mb:[{mb:[E]}],ml:[{ml:[E]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Yi]},Yi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Yi,Gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",ch]}],"font-family":[{font:[cu]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ha,ch]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[_]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[_]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...N(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,Gi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:X()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[_]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...F(),tF]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",eF]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[b]}],"gradient-via-pos":[{via:[b]}],"gradient-to-pos":[{to:[b]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[_]}],"border-style":[{border:[...N(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[_]}],"divide-style":[{divide:N()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...N()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,Gi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[_]}],"ring-offset-w":[{"ring-offset":[oo,Gi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Yi,oF]}],"shadow-color":[{shadow:[cu]}],opacity:[{opacity:[_]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Yi,Je]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[p]}],saturate:[{saturate:[C]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[p]}],"backdrop-opacity":[{"backdrop-opacity":[_]}],"backdrop-saturate":[{"backdrop-saturate":[C]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ce()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ce()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[R]}],"scale-x":[{"scale-x":[R]}],"scale-y":[{"scale-y":[R]}],rotate:[{rotate:[lu,Je]}],"translate-x":[{"translate-x":[D]}],"translate-y":[{"translate-y":[D]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":X()}],"scroll-mx":[{"scroll-mx":X()}],"scroll-my":[{"scroll-my":X()}],"scroll-ms":[{"scroll-ms":X()}],"scroll-me":[{"scroll-me":X()}],"scroll-mt":[{"scroll-mt":X()}],"scroll-mr":[{"scroll-mr":X()}],"scroll-mb":[{"scroll-mb":X()}],"scroll-ml":[{"scroll-ml":X()}],"scroll-p":[{"scroll-p":X()}],"scroll-px":[{"scroll-px":X()}],"scroll-py":[{"scroll-py":X()}],"scroll-ps":[{"scroll-ps":X()}],"scroll-pe":[{"scroll-pe":X()}],"scroll-pt":[{"scroll-pt":X()}],"scroll-pr":[{"scroll-pr":X()}],"scroll-pb":[{"scroll-pb":X()}],"scroll-pl":[{"scroll-pl":X()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,Gi,ch]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const tx=HL(lF),cF=40,fs="inpaint",uh="diffusers_sd",oC="diffusers_sdxl",dh="diffusers_sd_inpaint",iC="diffusers_sdxl_inpaint",d0="diffusers_other",Xy="#ffcc00bb",sC="ldm",aC="cv2",Gk="Fantasy-Studio/Paint-by-Example",uF="timbrooks/instruct-pix2pix",dF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",fF="Sanster/AnyText",hF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return tx(Bk(e))}function pF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function lC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function mF(e){const t=URL.createObjectURL(e),n=new Image;return await Vh(n,t),n}function cC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function gF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function Nu(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function vF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function yF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const wF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function uC(e){return e.nativeEvent.button===2}function dC(e){return e.nativeEvent.button===1}async function xF(e){const t=await yF(e,"image/png");try{await wF(t)}catch{console.log("Copy image failed!")}}function bF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function f0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function Yk(e,t,n=Xy){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Wh=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{Yk(s,l,o)}),i},Du=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function Xk(e,t){return function(){return e.apply(t,arguments)}}const{toString:SF}=Object.prototype,{getPrototypeOf:nx}=Object,Tm=(e=>t=>{const n=SF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),ei=e=>(e=e.toLowerCase(),t=>Tm(t)===e),Pm=e=>t=>typeof t===e,{isArray:Sc}=Array,rd=Pm("undefined");function _F(e){return e!==null&&!rd(e)&&e.constructor!==null&&!rd(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Zk=ei("ArrayBuffer");function EF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Zk(e.buffer),t}const CF=Pm("string"),Kr=Pm("function"),qk=Pm("number"),Am=e=>e!==null&&typeof e=="object",$F=e=>e===!0||e===!1,Hh=e=>{if(Tm(e)!=="object")return!1;const t=nx(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},RF=ei("Date"),kF=ei("File"),TF=ei("Blob"),PF=ei("FileList"),AF=e=>Am(e)&&Kr(e.pipe),MF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=Tm(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},OF=ei("URLSearchParams"),NF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Nd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),Sc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const Jk=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!rd(e)&&e!==Jk;function Zy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&Qk(t,o)||o;Hh(t[i])&&Hh(r)?t[i]=Zy(t[i],r):Hh(r)?t[i]=Zy({},r):Sc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(Nd(t,(o,i)=>{n&&Kr(o)?e[i]=Xk(o,n):e[i]=o},{allOwnKeys:r}),e),IF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),LF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},FF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&nx(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},jF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zF=e=>{if(!e)return null;if(Sc(e))return e;let t=e.length;if(!qk(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},BF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&nx(Uint8Array)),UF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},VF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},WF=ei("HTMLFormElement"),HF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),fC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),KF=ei("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};Nd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},GF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},YF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return Sc(e)?r(e):r(String(e).split(t)),n},XF=()=>{},ZF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),h0="abcdefghijklmnopqrstuvwxyz",hC="0123456789",nT={DIGIT:hC,ALPHA:h0,ALPHA_DIGIT:h0+h0.toUpperCase()+hC},qF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function QF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const JF=e=>{const t=new Array(10),n=(r,o)=>{if(Am(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=Sc(r)?[]:{};return Nd(r,(s,l)=>{const u=n(s,o+1);!rd(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},ej=ei("AsyncFunction"),tj=e=>e&&(Am(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:Sc,isArrayBuffer:Zk,isBuffer:_F,isFormData:MF,isArrayBufferView:EF,isString:CF,isNumber:qk,isBoolean:$F,isObject:Am,isPlainObject:Hh,isUndefined:rd,isDate:RF,isFile:kF,isBlob:TF,isRegExp:KF,isFunction:Kr,isStream:AF,isURLSearchParams:OF,isTypedArray:BF,isFileList:PF,forEach:Nd,merge:Zy,extend:DF,trim:NF,stripBOM:IF,inherits:LF,toFlatObject:FF,kindOf:Tm,kindOfTest:ei,endsWith:jF,toArray:zF,forEachEntry:UF,matchAll:VF,isHTMLForm:WF,hasOwnProperty:fC,hasOwnProp:fC,reduceDescriptors:tT,freezeMethods:GF,toObjectSet:YF,toCamelCase:HF,noop:XF,toFiniteNumber:ZF,findKey:Qk,global:Jk,isContextDefined:eT,ALPHABET:nT,generateString:qF,isSpecCompliantForm:QF,toJSONObject:JF,isAsyncFn:ej,isThenable:tj};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const nj=null;function qy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function pC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function rj(e){return oe.isArray(e)&&!e.some(qy)}const oj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Mm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(S,E){return!oe.isUndefined(E[S])});const r=n.metaTokens,o=n.visitor||m,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function f(b){if(b===null)return"";if(oe.isDate(b))return b.toISOString();if(!u&&oe.isBlob(b))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(b)||oe.isTypedArray(b)?u&&typeof Blob=="function"?new Blob([b]):Buffer.from(b):b}function m(b,S,E){let _=b;if(b&&!E&&typeof b=="object"){if(oe.endsWith(S,"{}"))S=r?S:S.slice(0,-2),b=JSON.stringify(b);else if(oe.isArray(b)&&rj(b)||(oe.isFileList(b)||oe.endsWith(S,"[]"))&&(_=oe.toArray(b)))return S=iT(S),_.forEach(function(C,R){!(oe.isUndefined(C)||C===null)&&t.append(s===!0?pC([S],R,i):s===null?S:S+"[]",f(C))}),!1}return qy(b)?!0:(t.append(pC(E,S,i),f(b)),!1)}const p=[],g=Object.assign(oj,{defaultVisitor:m,convertValue:f,isVisitable:qy});function y(b,S){if(!oe.isUndefined(b)){if(p.indexOf(b)!==-1)throw Error("Circular reference detected in "+S.join("."));p.push(b),oe.forEach(b,function(_,x){(!(oe.isUndefined(_)||_===null)&&o.call(t,_,oe.isString(x)?x.trim():x,S,g))===!0&&y(_,S?S.concat(x):[x])}),p.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function mC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function rx(e,t){this._pairs=[],e&&Mm(e,this,t)}const sT=rx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,mC)}:mC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function ij(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||ij,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new rx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class sj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const gC=sj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},aj=typeof URLSearchParams<"u"?URLSearchParams:rx,lj=typeof FormData<"u"?FormData:null,cj=typeof Blob<"u"?Blob:null,uj={isBrowser:!0,classes:{URLSearchParams:aj,FormData:lj,Blob:cj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",dj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),fj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",hj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:dj,hasStandardBrowserWebWorkerEnv:fj},Symbol.toStringTag,{value:"Module"})),zo={...hj,...uj};function pj(e,t){return Mm(e,new zo.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return zo.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function mj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function gj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=gj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(mj(r),o,n,0)}),n}return null}function vj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const ox={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return pj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Mm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),vj(t)):t}],transformResponse:[function(t){const n=this.transitional||ox.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:zo.classes.FormData,Blob:zo.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{ox.headers[e]={}});const ix=ox,yj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),wj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&yj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},vC=Symbol("internals");function uu(e){return e&&String(e).trim().toLowerCase()}function Kh(e){return e===!1||e==null?e:oe.isArray(e)?e.map(Kh):String(e)}function xj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const bj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function p0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function Sj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function _j(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Om{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,f){const m=uu(u);if(!m)throw new Error("header name must be a non-empty string");const p=oe.findKey(o,m);(!p||o[p]===void 0||f===!0||f===void 0&&o[p]!==!1)&&(o[p||u]=Kh(l))}const s=(l,u)=>oe.forEach(l,(f,m)=>i(f,m,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!bj(t)?s(wj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return xj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=uu(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||p0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=uu(s),s){const l=oe.findKey(r,s);l&&(!n||p0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||p0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=Kh(o),delete n[i];return}const l=t?Sj(i):String(i).trim();l!==i&&delete n[i],n[l]=Kh(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[vC]=this[vC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=uu(s);r[l]||(_j(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Om.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Om.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Om);const xi=Om;function m0(e,t){const n=this||ix,r=t||n,o=xi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Dd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Dd,ut,{__CANCEL__:!0});function Ej(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const Cj=zo.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function $j(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Rj(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!$j(t)?Rj(e,t):t}const kj=zo.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function Tj(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function Pj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const f=Date.now(),m=r[i];s||(s=f),n[o]=u,r[o]=f;let p=i,g=0;for(;p!==o;)g+=n[p++],p=p%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),f-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),f=i<=s;n=i;const m={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&f?(s-i)/u:void 0,event:o};m[t?"download":"upload"]=!0,e(m)}}const Aj=typeof XMLHttpRequest<"u",Mj=Aj&&function(e){return new Promise(function(n,r){let o=e.data;const i=xi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function f(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let m;if(oe.isFormData(o)){if(zo.hasStandardBrowserEnv||zo.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((m=i.getContentType())!==!1){const[S,...E]=m?m.split(";").map(_=>_.trim()).filter(Boolean):[];i.setContentType([S||"multipart/form-data",...E].join("; "))}}let p=new XMLHttpRequest;if(e.auth){const S=e.auth.username||"",E=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(S+":"+E))}const g=fT(e.baseURL,e.url);p.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),p.timeout=e.timeout;function y(){if(!p)return;const S=xi.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),_={data:!s||s==="text"||s==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:S,config:e,request:p};Ej(function(C){n(C),f()},function(C){r(C),f()},_),p=null}if("onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(r(new ut("Request aborted",ut.ECONNABORTED,e,p)),p=null)},p.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,p)),p=null},p.ontimeout=function(){let E=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const _=e.transitional||lT;e.timeoutErrorMessage&&(E=e.timeoutErrorMessage),r(new ut(E,_.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,p)),p=null},zo.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&kj(g))){const S=e.xsrfHeaderName&&e.xsrfCookieName&&Cj.read(e.xsrfCookieName);S&&i.set(e.xsrfHeaderName,S)}o===void 0&&i.setContentType(null),"setRequestHeader"in p&&oe.forEach(i.toJSON(),function(E,_){p.setRequestHeader(_,E)}),oe.isUndefined(e.withCredentials)||(p.withCredentials=!!e.withCredentials),s&&s!=="json"&&(p.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&p.addEventListener("progress",yC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&p.upload&&p.upload.addEventListener("progress",yC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=S=>{p&&(r(!S||S.type?new Dd(null,e,p):S),p.abort(),p=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const b=Tj(g);if(b&&zo.protocols.indexOf(b)===-1){r(new ut("Unsupported protocol "+b+":",ut.ERR_BAD_REQUEST,e));return}p.send(o||null)})},Qy={http:nj,xhr:Mj};oe.forEach(Qy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const wC=e=>`- ${e}`,Oj=e=>oe.isFunction(e)||e===null||e===!1,hT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(wC).join(` +`):" "+wC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Qy};function g0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Dd(null,e)}function xC(e){return g0(e),e.headers=xi.from(e.headers),e.data=m0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),hT.getAdapter(e.adapter||ix.adapter)(e).then(function(r){return g0(e),r.data=m0.call(e,e.transformResponse,r),r.headers=xi.from(r.headers),r},function(r){return dT(r)||(g0(e),r&&r.response&&(r.response.data=m0.call(e,e.transformResponse,r.response),r.response.headers=xi.from(r.response.headers))),Promise.reject(r)})}const bC=e=>e instanceof xi?e.toJSON():e;function ic(e,t){t=t||{};const n={};function r(f,m,p){return oe.isPlainObject(f)&&oe.isPlainObject(m)?oe.merge.call({caseless:p},f,m):oe.isPlainObject(m)?oe.merge({},m):oe.isArray(m)?m.slice():m}function o(f,m,p){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f,p)}else return r(f,m,p)}function i(f,m){if(!oe.isUndefined(m))return r(void 0,m)}function s(f,m){if(oe.isUndefined(m)){if(!oe.isUndefined(f))return r(void 0,f)}else return r(void 0,m)}function l(f,m,p){if(p in t)return r(f,m);if(p in e)return r(void 0,f)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(f,m)=>o(bC(f),bC(m),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(m){const p=u[m]||o,g=p(e[m],t[m],m);oe.isUndefined(g)&&p!==l||(n[m]=g)}),n}const pT="1.6.2",sx={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{sx[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const SC={};sx.transitional=function(t,n,r){function o(i,s){return"[Axios v"+pT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!SC[s]&&(SC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Nj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Jy={assertOptions:Nj,validators:sx},Xi=Jy.validators;class Op{constructor(t){this.defaults=t,this.interceptors={request:new gC,response:new gC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=ic(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Jy.assertOptions(r,{silentJSONParsing:Xi.transitional(Xi.boolean),forcedJSONParsing:Xi.transitional(Xi.boolean),clarifyTimeoutError:Xi.transitional(Xi.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Jy.assertOptions(o,{encode:Xi.function,serialize:Xi.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],b=>{delete i[b]}),n.headers=xi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(S){typeof S.runWhen=="function"&&S.runWhen(n)===!1||(u=u&&S.synchronous,l.unshift(S.fulfilled,S.rejected))});const f=[];this.interceptors.response.forEach(function(S){f.push(S.fulfilled,S.rejected)});let m,p=0,g;if(!u){const b=[xC.bind(this),void 0];for(b.unshift.apply(b,l),b.push.apply(b,f),g=b.length,m=Promise.resolve(n);p{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Dd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ax(function(o){t=o}),cancel:t}}}const Dj=ax;function Ij(e){return function(n){return e.apply(null,n)}}function Lj(e){return oe.isObject(e)&&e.isAxiosError===!0}const e1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(e1).forEach(([e,t])=>{e1[t]=e});const Fj=e1;function mT(e){const t=new Gh(e),n=Xk(Gh.prototype.request,t);return oe.extend(n,Gh.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(ic(e,o))},n}const Qt=mT(ix);Qt.Axios=Gh;Qt.CanceledError=Dd;Qt.CancelToken=Dj;Qt.isCancel=dT;Qt.VERSION=pT;Qt.toFormData=Mm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Ij;Qt.isAxiosError=Lj;Qt.mergeConfig=ic;Qt.AxiosHeaders=xi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=hT.getAdapter;Qt.HttpStatusCode=Fj;Qt.default=Qt;const jj=Qt,Ls="/api/v1",_c=jj.create({baseURL:Ls});async function zj(e,t,n,r,o,i=null){const s=await Du(e),l=await Du(o),u=i?await Du(i):null,f=await fetch(`${Ls}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?Ol.outpainting:t.powerpaintTask})});if(f.ok){const p=await f.blob();return{blob:URL.createObjectURL(p),seed:f.headers.get("X-Seed")}}const m=await f.json();throw new Error(`Something went wrong: ${m.errors}`)}async function gT(){return(await _c.get("/server-config")).data}async function Bj(e){return(await _c.post("/model",{name:e})).data}async function v0(e,t){return _c.post("/switch_plugin_model",{plugin_name:e,model_name:t})}async function Uj(){return(await _c.get("/model")).data}async function vT(e,t,n,r,o){const i=await Du(n),l=await fetch(`${Ls}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const f=await l.blob();return{blob:URL.createObjectURL(f)}}const u=await l.json();throw new Error(u)}async function Vj(e,t){const n=await fetch(`${Ls}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Wj(e){return(await _c.get("medias",{params:{tab:e}})).data}async function Hj(e,t,n){const r=await Nu(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ls}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Kj(e){const t=new FormData;return t.append("file",e),(await _c.post("/gen-info",t)).data}async function Gj(e,t,n){const r=await Du(e),o=await fetch(`${Ls}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=d.useState(null),n=d.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ls}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)return;const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return d.useEffect(()=>{n()},[n]),e}function _o(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Xj=["color"],Zj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Xj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],yT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Qj=["color"],Jj=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,Qj);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),ez=["color"],tz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,ez);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),nz=["color"],rz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,nz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],wT=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,oz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),iz=["color"],sz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,iz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),az=["color"],lz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,az);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),cz=["color"],uz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,cz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),dz=["color"],fz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,dz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),hz=["color"],pz=d.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=_o(e,hz);return d.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),d.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>mz(n,t))}function Be(...e){return d.useCallback(Nm(...e),e)}const Zo=d.forwardRef((e,t)=>{const{children:n,...r}=e,o=d.Children.toArray(n),i=o.find(gz);if(i){const s=i.props.children,l=o.map(u=>u===i?d.Children.count(s)>1?d.Children.only(null):d.isValidElement(s)?s.props.children:null:u);return d.createElement(t1,Y({},r,{ref:t}),d.isValidElement(s)?d.cloneElement(s,void 0,l):null)}return d.createElement(t1,Y({},r,{ref:t}),n)});Zo.displayName="Slot";const t1=d.forwardRef((e,t)=>{const{children:n,...r}=e;return d.isValidElement(n)?d.cloneElement(n,{...vz(r,n.props),ref:t?Nm(t,n.ref):n.ref}):d.Children.count(n)>1?d.Children.only(null):null});t1.displayName="SlotClone";const lx=({children:e})=>d.createElement(d.Fragment,null,e);function gz(e){return d.isValidElement(e)&&e.type===lx}function vz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const _C=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,EC=Bk,Dm=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return EC(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(f=>{const m=n==null?void 0:n[f],p=i==null?void 0:i[f];if(m===null)return null;const g=_C(m)||_C(p);return o[f][g]}),l=n&&Object.entries(n).reduce((f,m)=>{let[p,g]=m;return g===void 0||(f[p]=g),f},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((f,m)=>{let{class:p,className:g,...y}=m;return Object.entries(y).every(b=>{let[S,E]=b;return Array.isArray(E)?E.includes({...i,...l}[S]):{...i,...l}[S]===E})?[...f,p,g]:f},[]);return EC(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var yz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function wz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const od=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return od(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return od(r)(n)}}}},xz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:E=>E,version:0,merge:(E,_)=>({..._,...E}),...t},s=!1;const l=new Set,u=new Set;let f;try{f=i.getStorage()}catch{}if(!f)return e((...E)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...E)},r,o);const m=od(i.serialize),p=()=>{const E=i.partialize({...r()});let _;const x=m({state:E,version:i.version}).then(C=>f.setItem(i.name,C)).catch(C=>{_=C});if(_)throw _;return x},g=o.setState;o.setState=(E,_)=>{g(E,_),p()};const y=e((...E)=>{n(...E),p()},r,o);let b;const S=()=>{var E;if(!f)return;s=!1,l.forEach(x=>x(r()));const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,r()))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)return i.deserialize(x)}).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return b=i.merge(x,(C=r())!=null?C:y),n(b,!0),p()}).then(()=>{_==null||_(b,void 0),s=!0,u.forEach(x=>x(b))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:E=>{i={...i,...E},E.getStorage&&(f=E.getStorage())},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>S(),hasHydrated:()=>s,onHydrate:E=>(l.add(E),()=>{l.delete(E)}),onFinishHydration:E=>(u.add(E),()=>{u.delete(E)})},S(),b||y},bz=(e,t)=>(n,r,o)=>{let i={storage:wz(()=>localStorage),partialize:S=>S,version:0,merge:(S,E)=>({...E,...S}),...t},s=!1;const l=new Set,u=new Set;let f=i.storage;if(!f)return e((...S)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...S)},r,o);const m=()=>{const S=i.partialize({...r()});return f.setItem(i.name,{state:S,version:i.version})},p=o.setState;o.setState=(S,E)=>{p(S,E),m()};const g=e((...S)=>{n(...S),m()},r,o);let y;const b=()=>{var S,E;if(!f)return;s=!1,l.forEach(x=>{var C;return x((C=r())!=null?C:g)});const _=((E=i.onRehydrateStorage)==null?void 0:E.call(i,(S=r())!=null?S:g))||void 0;return od(f.getItem.bind(f))(i.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==i.version){if(i.migrate)return i.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var C;return y=i.merge(x,(C=r())!=null?C:g),n(y,!0),m()}).then(()=>{_==null||_(y,void 0),y=r(),s=!0,u.forEach(x=>x(y))}).catch(x=>{_==null||_(void 0,x)})};return o.persist={setOptions:S=>{i={...i,...S},S.storage&&(f=S.storage)},clearStorage:()=>{f==null||f.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>b(),hasHydrated:()=>s,onHydrate:S=>(l.add(S),()=>{l.delete(S)}),onFinishHydration:S=>(u.add(S),()=>{u.delete(S)})},i.skipHydration||b(),y||g},Sz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((yz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),xz(e,t)):bz(e,t),_z=Sz;function Ez(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Im(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Lm(e)?2:Fm(e)?3:0}function n1(e,t){return Im(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function ST(e,t,n){const r=Im(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function $z(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Lm(e){return e instanceof Map}function Fm(e){return e instanceof Set}function ra(e){return e.copy_||e.base_}function r1(e,t){if(Lm(e))return new Map(e);if(Fm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&bT(e))return sc(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=Rz),Object.freeze(e),t&&id(e,(n,r)=>cx(r,!0))),e}function Rz(){po(2)}function jm(e){return Object.isFrozen(e)}var kz={};function Oa(e){const t=kz[e];return t||po(0,e),t}var sd;function _T(){return sd}function Tz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function $C(e,t){t&&(Oa("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function o1(e){i1(e),e.drafts_.forEach(Pz),e.drafts_=null}function i1(e){e===sd&&(sd=e.parent_)}function RC(e){return sd=Tz(sd,e)}function Pz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function kC(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(o1(t),po(4)),Ma(e)&&(e=Np(t,e),t.parent_||Dp(t,e)),t.patches_&&Oa("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Np(t,n,[]),o1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==xT?e:void 0}function Np(e,t,n){if(jm(t))return t;const r=t[wr];if(!r)return id(t,(o,i)=>TC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Dp(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),id(i,(l,u)=>TC(e,r,o,l,u,n,s)),Dp(e,o,!1),n&&e.patches_&&Oa("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function TC(e,t,n,r,o,i,s){if(ac(o)){const l=i&&t&&t.type_!==3&&!n1(t.assigned_,r)?i.concat(r):void 0,u=Np(e,o,l);if(ST(n,r,u),ac(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if(Ma(o)&&!jm(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Np(e,o),(!t||!t.scope_.parent_)&&Dp(e,o)}}function Dp(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&cx(t,n)}function Az(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=ux;n&&(o=[r],i=ad);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var ux={get(e,t){if(t===wr)return e;const n=ra(e);if(!n1(n,t))return Mz(e,n,t);const r=n[t];return e.finalized_||!Ma(r)?r:r===y0(e.base_,t)?(w0(e),e.copy_[t]=a1(r,e)):r},has(e,t){return t in ra(e)},ownKeys(e){return Reflect.ownKeys(ra(e))},set(e,t,n){const r=ET(ra(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=y0(ra(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if($z(n,o)&&(n!==void 0||n1(e.base_,t)))return!0;w0(e),s1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return y0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,w0(e),s1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=ra(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){po(11)},getPrototypeOf(e){return sc(e.base_)},setPrototypeOf(){po(12)}},ad={};id(ux,(e,t)=>{ad[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ad.deleteProperty=function(e,t){return ad.set.call(this,e,t,void 0)};ad.set=function(e,t,n){return ux.set.call(this,e[0],t,n,e[0])};function y0(e,t){const n=e[wr];return(n?ra(n):e)[t]}function Mz(e,t,n){var o;const r=ET(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ET(e,t){if(!(t in e))return;let n=sc(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=sc(n)}}function s1(e){e.modified_||(e.modified_=!0,e.parent_&&s1(e.parent_))}function w0(e){e.copy_||(e.copy_=r1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...f){return s.produce(u,m=>n.call(this,m,...f))}}typeof n!="function"&&po(6),r!==void 0&&typeof r!="function"&&po(7);let o;if(Ma(t)){const i=RC(this),s=a1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?o1(i):i1(i)}return $C(i,r),kC(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===xT&&(o=void 0),this.autoFreeze_&&cx(o,!0),r){const i=[],s=[];Oa("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else po(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){Ma(e)||po(8),ac(e)&&(e=Nz(e));const t=RC(this),n=a1(e,void 0);return n[wr].isManual_=!0,i1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&po(9);const{scope_:r}=n;return $C(r,t),kC(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=Oa("Patches").applyPatches_;return ac(e)?r(e,t):this.produce(e,o=>r(o,t))}};function a1(e,t){const n=Lm(e)?Oa("MapSet").proxyMap_(e,t):Fm(e)?Oa("MapSet").proxySet_(e,t):Az(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Nz(e){return ac(e)||po(10,e),CT(e)}function CT(e){if(!Ma(e)||jm(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=r1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=r1(e,!0);return id(n,(r,o)=>{ST(n,r,CT(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Dz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Iz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Dz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Lz=Iz;var $T={exports:{}},RT={},kT={exports:{}},TT={};/** + * @license React + * use-sync-external-store-shim.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. + */var lc=d;function Fz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var jz=typeof Object.is=="function"?Object.is:Fz,zz=lc.useState,Bz=lc.useEffect,Uz=lc.useLayoutEffect,Vz=lc.useDebugValue;function Wz(e,t){var n=t(),r=zz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Uz(function(){o.value=n,o.getSnapshot=t,x0(o)&&i({inst:o})},[e,n,t]),Bz(function(){return x0(o)&&i({inst:o}),e(function(){x0(o)&&i({inst:o})})},[e]),Vz(n),n}function x0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!jz(e,n)}catch{return!0}}function Hz(e,t){return t()}var Kz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Hz:Wz;TT.useSyncExternalStore=lc.useSyncExternalStore!==void 0?lc.useSyncExternalStore:Kz;kT.exports=TT;var Gz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var zm=d,Yz=Gz;function Xz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Zz=typeof Object.is=="function"?Object.is:Xz,qz=Yz.useSyncExternalStore,Qz=zm.useRef,Jz=zm.useEffect,eB=zm.useMemo,tB=zm.useDebugValue;RT.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=Qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=eB(function(){function u(y){if(!f){if(f=!0,m=y,y=r(y),o!==void 0&&s.hasValue){var b=s.value;if(o(b,y))return p=b}return p=y}if(b=p,Zz(m,y))return b;var S=r(y);return o!==void 0&&o(b,S)?b:(m=y,p=S)}var f=!1,m,p,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=qz(e,i[0],i[1]);return Jz(function(){s.hasValue=!0,s.value=l},[l]),tB(l),l};$T.exports=RT;var nB=$T.exports;const rB=dm(nB);var oB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const PC=e=>{let t;const n=new Set,r=(u,f)=>{const m=typeof u=="function"?u(t):u;if(!Object.is(m,t)){const p=t;t=f??typeof m!="object"?m:Object.assign({},t,m),n.forEach(g=>g(t,p))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(oB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},iB=e=>e?PC(e):PC,{useDebugValue:sB}=Fe,{useSyncExternalStoreWithSelector:aB}=rB;function lB(e,t=e.getState,n){const r=aB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return sB(r),r}const AC=(e,t)=>{const n=iB(e),r=(o,i=t)=>lB(n,o,i);return Object.assign(r,n),r},cB=(e,t)=>e?AC(e,t):AC,uB=1,dB=1e6;let b0=0;function fB(){return b0=(b0+1)%Number.MAX_VALUE,b0.toString()}const S0=new Map,MC=e=>{if(S0.has(e))return;const t=setTimeout(()=>{S0.delete(e),Iu({type:"REMOVE_TOAST",toastId:e})},dB);S0.set(e,t)},hB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,uB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?MC(n):e.toasts.forEach(r=>{MC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Yh=[];let Xh={toasts:[]};function Iu(e){Xh=hB(Xh,e),Yh.forEach(t=>{t(Xh)})}function ul({...e}){const t=fB(),n=o=>Iu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Iu({type:"DISMISS_TOAST",toastId:t});return Iu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Id(){const[e,t]=d.useState(Xh);return d.useEffect(()=>(Yh.push(t),()=>{const n=Yh.indexOf(t);n>-1&&Yh.splice(n,1)}),[e]),{...e,toast:ul,dismiss:n=>Iu({type:"DISMISS_TOAST",toastId:n})}}const ea={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:cF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:Es.CTIME,sortOrder:Ou.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],modelInfos:[],removeBGModel:"briaai/RMBG-1.4",removeBGModels:[],realesrganModel:"realesr-general-x4v3",realesrganModels:[],interactiveSegModel:"vit_b",interactiveSegModels:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:Ln.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Qw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:Jw.INPAINT_NS,prompt:"",negativePrompt:hF,seed:42,seedFixed:!1,sdMaskBlur:12,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:Ol.text_guided,adjustMaskKernelSize:12}},bt=cB()(_z(Lz((e,t)=>({...ea,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Wh(s,l,[n],o,Xy);try{const f=await cC(u);e(m=>{m.editorState.temporaryMasks.push(f)})}catch(f){console.error(f);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await Nu(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:f}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&f.height===s&&f.width===i)return;const{lastLineGroup:m,curLineGroup:p,lineGroups:g,renders:y,prevExtraMasks:b,extraMasks:S}=t().editorState,E=p.length===0&&S.length===0&&!l.showExtender;let _=[],x=[];if(E===!0?(x=m,_=b):(x=p,_=S),x.length===0&&_===null&&!l.showExtender){ul({variant:"destructive",description:"Please draw mask on picture"});return}const C=[...g,x];e(M=>{M.isInpainting=!0});let R=r;if(E===!0){if(y.length>1){const M=y[y.length-2];R=await Nu(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];R=await Nu(M.currentSrc,r.name,r.type)}const P=Wh(i,s,[x],_);if(E){const M=await cC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await zj(R,l,u,f,lC(P.toDataURL()),o),{blob:A,seed:D}=M;D&&t().setSeed(parseInt(D,10));const U=new Image;await Vh(U,A);const W=[...y,U];t().setImageSize(U.width,U.height),t().updateEditorState({renders:W,lineGroups:C,lastLineGroup:x,curLineGroup:[],extraMasks:[],prevExtraMasks:_})}catch(M){ul({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),f=await vT(n,r,u,o.upscale),{blob:m}=f;if(n){const y=new Image;await Vh(y,m),e(b=>{b.editorState.extraMasks.push(y)})}else{const y=new Image;await Vh(y,m),t().setImageSize(y.width,y.height);const b=[...i,y],S=[...s,[]];t().updateEditorState({renders:b,lineGroups:S})}const g=new Date().getTime()-l.getTime();ul({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){ul({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==fs},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==fs,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==fs&&n.name!==Gk},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(ea.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...ea.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Kj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){ul({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=ea.interactiveSegState,r.editorState=ea.editorState,r.cropperState=ea.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...ea.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:f,imageHeight:m}=t();switch(l=f,u=m,n){case Ln.x:i=-Math.ceil(f*(r-1)/2),l=Math.ceil(f*r);break;case Ln.y:s=-Math.ceil(m*(r-1)/2),u=Math.ceil(m*r);break;case Ln.xy:i=-Math.ceil(f*(r-1)/2),s=-Math.ceil(m*(r-1)/2),l=Math.ceil(f*r),u=Math.ceil(m*r);break}e(p=>{p.extenderState.x=i,p.extenderState.y=s,p.extenderState.width=l,p.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Wh(r,o,[i],s,Xy),f=lC(u.toDataURL()),m=await Gj(f,n,l),p=await mF(m);e(g=>{g.editorState.extraMasks=[p],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Ez),Ld=d.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Ld.displayName="Input";const Yn=d.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=d.useState(e.toString());d.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let m=u.target.value;if(t){if(m=m.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),m.length===0){n(0);return}n(parseFloat(m))}else{if(m=m.replace(/\D/g,""),m.length===0){n(0);return}n(parseInt(m,10))}s(m)};return v.jsx(Ld,{ref:o,value:i,onInput:l,...r})});function de(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=d.createContext(t);function r(i){const{children:s,...l}=i,u=d.useMemo(()=>l,Object.values(l));return d.createElement(n.Provider,{value:u},s)}function o(i){const s=d.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function Mn(e,t=[]){let n=[];function r(i,s){const l=d.createContext(s),u=n.length;n=[...n,s];function f(p){const{scope:g,children:y,...b}=p,S=(g==null?void 0:g[e][u])||l,E=d.useMemo(()=>b,Object.values(b));return d.createElement(S.Provider,{value:E},y)}function m(p,g){const y=(g==null?void 0:g[e][u])||l,b=d.useContext(y);if(b)return b;if(s!==void 0)return s;throw new Error(`\`${p}\` must be used within \`${i}\``)}return f.displayName=i+"Provider",[f,m]}const o=()=>{const i=n.map(s=>d.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return d.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,mB(o,...t)]}function mB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:f})=>{const p=u(i)[`__scope${f}`];return{...l,...p}},{});return d.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const gB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=gB.reduce((e,t)=>{const n=d.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Zo:t;return d.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),d.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function dx(e,t){e&&Is.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=d.useRef(e);return d.useEffect(()=>{t.current=e}),d.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function vB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);d.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const l1="dismissableLayer.update",yB="dismissableLayer.pointerDownOutside",wB="dismissableLayer.focusOutside";let OC;const PT=d.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),Ec=d.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...f}=e,m=d.useContext(PT),[p,g]=d.useState(null),y=(n=p==null?void 0:p.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,b]=d.useState({}),S=Be(t,D=>g(D)),E=Array.from(m.layers),[_]=[...m.layersWithOutsidePointerEventsDisabled].slice(-1),x=E.indexOf(_),C=p?E.indexOf(p):-1,R=m.layersWithOutsidePointerEventsDisabled.size>0,P=C>=x,M=bB(D=>{const U=D.target,W=[...m.branches].some(q=>q.contains(U));!P||W||(i==null||i(D),l==null||l(D),D.defaultPrevented||u==null||u())},y),A=SB(D=>{const U=D.target;[...m.branches].some(q=>q.contains(U))||(s==null||s(D),l==null||l(D),D.defaultPrevented||u==null||u())},y);return vB(D=>{C===m.layers.size-1&&(o==null||o(D),!D.defaultPrevented&&u&&(D.preventDefault(),u()))},y),d.useEffect(()=>{if(p)return r&&(m.layersWithOutsidePointerEventsDisabled.size===0&&(OC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),m.layersWithOutsidePointerEventsDisabled.add(p)),m.layers.add(p),NC(),()=>{r&&m.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=OC)}},[p,y,r,m]),d.useEffect(()=>()=>{p&&(m.layers.delete(p),m.layersWithOutsidePointerEventsDisabled.delete(p),NC())},[p,m]),d.useEffect(()=>{const D=()=>b({});return document.addEventListener(l1,D),()=>document.removeEventListener(l1,D)},[]),d.createElement(Pe.div,Y({},f,{ref:S,style:{pointerEvents:R?P?"auto":"none":void 0,...e.style},onFocusCapture:de(e.onFocusCapture,A.onFocusCapture),onBlurCapture:de(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:de(e.onPointerDownCapture,M.onPointerDownCapture)}))}),xB=d.forwardRef((e,t)=>{const n=d.useContext(PT),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),d.createElement(Pe.div,Y({},e,{ref:o}))});function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1),o=d.useRef(()=>{});return d.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let m=function(){AT(yB,n,f,{discrete:!0})};var u=m;const f={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=m,t.addEventListener("click",o.current,{once:!0})):m()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function SB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=d.useRef(!1);return d.useEffect(()=>{const o=i=>{i.target&&!r.current&&AT(wB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function NC(){const e=new CustomEvent(l1);document.dispatchEvent(e)}function AT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const _B=Ec,EB=xB,An=globalThis!=null&&globalThis.document?d.useLayoutEffect:()=>{},CB=UD.useId||(()=>{});let $B=0;function nr(e){const[t,n]=d.useState(CB());return An(()=>{e||n(r=>r??String($B++))},[e]),e||(t?`radix-${t}`:"")}const RB=["top","right","bottom","left"],Ts=Math.min,hr=Math.max,Ip=Math.round,fh=Math.floor,Ps=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},TB={start:"end",end:"start"};function c1(e,t,n){return hr(e,Ts(t,n))}function Ci(e,t){return typeof e=="function"?e(t):e}function $i(e){return e.split("-")[0]}function Cc(e){return e.split("-")[1]}function fx(e){return e==="x"?"y":"x"}function hx(e){return e==="y"?"height":"width"}function $c(e){return["top","bottom"].includes($i(e))?"y":"x"}function px(e){return fx($c(e))}function PB(e,t,n){n===void 0&&(n=!1);const r=Cc(e),o=px(e),i=hx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Lp(s)),[s,Lp(s)]}function AB(e){const t=Lp(e);return[u1(e),t,u1(t)]}function u1(e){return e.replace(/start|end/g,t=>TB[t])}function MB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=Cc(e);let i=MB($i(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(u1)))),i}function Lp(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function NB(e){return{top:0,right:0,bottom:0,left:0,...e}}function MT(e){return typeof e!="number"?NB(e):{top:e,right:e,bottom:e,left:e}}function Fp(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function DC(e,t,n){let{reference:r,floating:o}=e;const i=$c(t),s=px(t),l=hx(s),u=$i(t),f=i==="y",m=r.x+r.width/2-o.width/2,p=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:m,y:r.y-o.height};break;case"bottom":y={x:m,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:p};break;case"left":y={x:r.x-o.width,y:p};break;default:y={x:r.x,y:r.y}}switch(Cc(t)){case"start":y[s]-=g*(n&&f?-1:1);break;case"end":y[s]+=g*(n&&f?-1:1);break}return y}const DB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let f=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:m,y:p}=DC(f,r,u),g=r,y={},b=0;for(let S=0;S({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:f,padding:m=0}=Ci(e,t)||{};if(f==null)return{};const p=MT(m),g={x:n,y:r},y=px(o),b=hx(y),S=await s.getDimensions(f),E=y==="y",_=E?"top":"left",x=E?"bottom":"right",C=E?"clientHeight":"clientWidth",R=i.reference[b]+i.reference[y]-g[y]-i.floating[b],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(f));let A=M?M[C]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[C]||i.floating[b]);const D=R/2-P/2,U=A/2-S[b]/2-1,W=Ts(p[_],U),q=Ts(p[x],U),X=W,ae=A-S[b]-q,V=A/2-S[b]/2+D,F=c1(X,V,ae),N=!u.arrow&&Cc(o)!=null&&V!=F&&i.reference[b]/2-(VX<=0)){var U,W;const X=(((U=i.flip)==null?void 0:U.index)||0)+1,ae=P[X];if(ae)return{data:{index:X,overflows:D},reset:{placement:ae}};let V=(W=D.filter(F=>F.overflows[0]<=0).sort((F,N)=>F.overflows[1]-N.overflows[1])[0])==null?void 0:W.placement;if(!V)switch(y){case"bestFit":{var q;const F=(q=D.map(N=>[N.placement,N.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((N,ie)=>N[1]-ie[1])[0])==null?void 0:q[0];F&&(V=F);break}case"initialPlacement":V=l;break}if(o!==V)return{reset:{placement:V}}}return{}}}};function LC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function FC(e){return RB.some(t=>e[t]>=0)}const LB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=Ci(e,t);switch(r){case"referenceHidden":{const i=await ld(t,{...o,elementContext:"reference"}),s=LC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:FC(s)}}}case"escaped":{const i=await ld(t,{...o,altBoundary:!0}),s=LC(i,n.floating);return{data:{escapedOffsets:s,escaped:FC(s)}}}default:return{}}}}};async function FB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=$i(n),l=Cc(n),u=$c(n)==="y",f=["left","top"].includes(s)?-1:1,m=i&&u?-1:1,p=Ci(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...p};return l&&typeof b=="number"&&(y=l==="end"?b*-1:b),u?{x:y*m,y:g*f}:{x:g*f,y:y*m}}const jB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await FB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},zB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:E=>{let{x:_,y:x}=E;return{x:_,y:x}}},...u}=Ci(e,t),f={x:n,y:r},m=await ld(t,u),p=$c($i(o)),g=fx(p);let y=f[g],b=f[p];if(i){const E=g==="y"?"top":"left",_=g==="y"?"bottom":"right",x=y+m[E],C=y-m[_];y=c1(x,y,C)}if(s){const E=p==="y"?"top":"left",_=p==="y"?"bottom":"right",x=b+m[E],C=b-m[_];b=c1(x,b,C)}const S=l.fn({...t,[g]:y,[p]:b});return{...S,data:{x:S.x-n,y:S.y-r}}}}},BB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:f=!0}=Ci(e,t),m={x:n,y:r},p=$c(o),g=fx(p);let y=m[g],b=m[p];const S=Ci(l,t),E=typeof S=="number"?{mainAxis:S,crossAxis:0}:{mainAxis:0,crossAxis:0,...S};if(u){const C=g==="y"?"height":"width",R=i.reference[g]-i.floating[C]+E.mainAxis,P=i.reference[g]+i.reference[C]-E.mainAxis;yP&&(y=P)}if(f){var _,x;const C=g==="y"?"width":"height",R=["top","left"].includes($i(o)),P=i.reference[p]-i.floating[C]+(R&&((_=s.offset)==null?void 0:_[p])||0)+(R?0:E.crossAxis),M=i.reference[p]+i.reference[C]+(R?0:((x=s.offset)==null?void 0:x[p])||0)-(R?E.crossAxis:0);bM&&(b=M)}return{[g]:y,[p]:b}}}},UB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=Ci(e,t),u=await ld(t,l),f=$i(n),m=Cc(n),p=$c(n)==="y",{width:g,height:y}=r.floating;let b,S;f==="top"||f==="bottom"?(b=f,S=m===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(S=f,b=m==="end"?"top":"bottom");const E=y-u[b],_=g-u[S],x=!t.middlewareData.shift;let C=E,R=_;if(p){const M=g-u.left-u.right;R=m||x?Ts(_,M):M}else{const M=y-u.top-u.bottom;C=m||x?Ts(E,M):M}if(x&&!m){const M=hr(u.left,0),A=hr(u.right,0),D=hr(u.top,0),U=hr(u.bottom,0);p?R=g-2*(M!==0||A!==0?M+A:hr(u.left,u.right)):C=y-2*(D!==0||U!==0?D+U:hr(u.top,u.bottom))}await s({...t,availableWidth:R,availableHeight:C});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function As(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Mi(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function Ri(e){return e instanceof Element||e instanceof vr(e).Element}function qo(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function jC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Fd(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function VB(e){return["table","td","th"].includes(As(e))}function mx(e){const t=gx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function WB(e){let t=cc(e);for(;qo(t)&&!Bm(t);){if(mx(t))return t;t=cc(t)}return null}function gx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Bm(e){return["html","body","#document"].includes(As(e))}function Xr(e){return vr(e).getComputedStyle(e)}function Um(e){return Ri(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function cc(e){if(As(e)==="html")return e;const t=e.assignedSlot||e.parentNode||jC(e)&&e.host||Mi(e);return jC(t)?t.host:t}function NT(e){const t=cc(e);return Bm(t)?e.ownerDocument?e.ownerDocument.body:e.body:qo(t)&&Fd(t)?t:NT(t)}function cd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=NT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Fd(o)?o:[],s.frameElement&&n?cd(s.frameElement):[]):t.concat(o,cd(o,[],n))}function DT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=qo(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Ip(n)!==i||Ip(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function vx(e){return Ri(e)?e:e.contextElement}function Nl(e){const t=vx(e);if(!qo(t))return Ps(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=DT(t);let s=(i?Ip(n.width):n.width)/r,l=(i?Ip(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const HB=Ps(0);function IT(e){const t=vr(e);return!gx()||!t.visualViewport?HB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function KB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Na(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=vx(e);let s=Ps(1);t&&(r?Ri(r)&&(s=Nl(r)):s=Nl(e));const l=KB(i,n,r)?IT(i):Ps(0);let u=(o.left+l.x)/s.x,f=(o.top+l.y)/s.y,m=o.width/s.x,p=o.height/s.y;if(i){const g=vr(i),y=r&&Ri(r)?vr(r):r;let b=g.frameElement;for(;b&&r&&y!==g;){const S=Nl(b),E=b.getBoundingClientRect(),_=Xr(b),x=E.left+(b.clientLeft+parseFloat(_.paddingLeft))*S.x,C=E.top+(b.clientTop+parseFloat(_.paddingTop))*S.y;u*=S.x,f*=S.y,m*=S.x,p*=S.y,u+=x,f+=C,b=vr(b).frameElement}}return Fp({width:m,height:p,x:u,y:f})}function GB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=qo(n),i=Mi(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=Ps(1);const u=Ps(0);if((o||!o&&r!=="fixed")&&((As(n)!=="body"||Fd(i))&&(s=Um(n)),qo(n))){const f=Na(n);l=Nl(n),u.x=f.x+n.clientLeft,u.y=f.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function LT(e){return Na(Mi(e)).left+Um(e).scrollLeft}function XB(e){const t=Mi(e),n=Um(e),r=e.ownerDocument.body,o=hr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=hr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+LT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=hr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function ZB(e,t){const n=vr(e),r=Mi(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const f=gx();(!f||f&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function qB(e,t){const n=Na(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=qo(e)?Nl(e):Ps(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,f=r*i.y;return{width:s,height:l,x:u,y:f}}function zC(e,t,n){let r;if(t==="viewport")r=ZB(e,n);else if(t==="document")r=XB(Mi(e));else if(Ri(t))r=qB(t,n);else{const o=IT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Fp(r)}function FT(e,t){const n=cc(e);return n===t||!Ri(n)||Bm(n)?!1:Xr(n).position==="fixed"||FT(n,t)}function QB(e,t){const n=t.get(e);if(n)return n;let r=cd(e,[],!1).filter(l=>Ri(l)&&As(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?cc(e):e;for(;Ri(s)&&!Bm(s);){const l=Xr(s),u=mx(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Fd(s)&&!u&&FT(e,s))?r=r.filter(m=>m!==s):o=l,s=cc(s)}return t.set(e,r),r}function JB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?QB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((f,m)=>{const p=zC(t,m,o);return f.top=hr(p.top,f.top),f.right=Ts(p.right,f.right),f.bottom=Ts(p.bottom,f.bottom),f.left=hr(p.left,f.left),f},zC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function eU(e){return DT(e)}function tU(e,t,n){const r=qo(t),o=Mi(t),i=n==="fixed",s=Na(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=Ps(0);if(r||!r&&!i)if((As(t)!=="body"||Fd(o))&&(l=Um(t)),r){const f=Na(t,!0,i,t);u.x=f.x+t.clientLeft,u.y=f.y+t.clientTop}else o&&(u.x=LT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function BC(e,t){return!qo(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function jT(e,t){const n=vr(e);if(!qo(e))return n;let r=BC(e,t);for(;r&&VB(r)&&Xr(r).position==="static";)r=BC(r,t);return r&&(As(r)==="html"||As(r)==="body"&&Xr(r).position==="static"&&!mx(r))?n:r||WB(e)||n}const nU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||jT,i=this.getDimensions;return{reference:tU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function rU(e){return Xr(e).direction==="rtl"}const oU={convertOffsetParentRelativeRectToViewportRelativeRect:GB,getDocumentElement:Mi,getClippingRect:JB,getOffsetParent:jT,getElementRects:nU,getClientRects:YB,getDimensions:eU,getScale:Nl,isElement:Ri,isRTL:rU};function iU(e,t){let n=null,r;const o=Mi(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:f,top:m,width:p,height:g}=e.getBoundingClientRect();if(l||t(),!p||!g)return;const y=fh(m),b=fh(o.clientWidth-(f+p)),S=fh(o.clientHeight-(m+g)),E=fh(f),x={rootMargin:-y+"px "+-b+"px "+-S+"px "+-E+"px",threshold:hr(0,Ts(1,u))||1};let C=!0;function R(P){const M=P[0].intersectionRatio;if(M!==u){if(!C)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}C=!1}try{n=new IntersectionObserver(R,{...x,root:o.ownerDocument})}catch{n=new IntersectionObserver(R,x)}n.observe(e)}return s(!0),i}function sU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,f=vx(e),m=o||i?[...f?cd(f):[],...cd(t)]:[];m.forEach(_=>{o&&_.addEventListener("scroll",n,{passive:!0}),i&&_.addEventListener("resize",n)});const p=f&&l?iU(f,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(_=>{let[x]=_;x&&x.target===f&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),f&&!u&&y.observe(f),y.observe(t));let b,S=u?Na(e):null;u&&E();function E(){const _=Na(e);S&&(_.x!==S.x||_.y!==S.y||_.width!==S.width||_.height!==S.height)&&n(),S=_,b=requestAnimationFrame(E)}return n(),()=>{m.forEach(_=>{o&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),p&&p(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(b)}}const aU=(e,t,n)=>{const r=new Map,o={platform:oU,...n},i={...o.platform,_c:r};return DB(e,t,{...o,platform:i})},lU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?IC({element:r.current,padding:o}).fn(n):{}:r?IC({element:r,padding:o}).fn(n):{}}}};var Zh=typeof document<"u"?d.useLayoutEffect:d.useEffect;function jp(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!jp(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!jp(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function zT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function UC(e,t){const n=zT(e);return Math.round(t*n)/n}function VC(e){const t=d.useRef(e);return Zh(()=>{t.current=e}),t}function cU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:f}=e,[m,p]=d.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=d.useState(r);jp(g,r)||y(r);const[b,S]=d.useState(null),[E,_]=d.useState(null),x=d.useCallback(N=>{N!=M.current&&(M.current=N,S(N))},[S]),C=d.useCallback(N=>{N!==A.current&&(A.current=N,_(N))},[_]),R=i||b,P=s||E,M=d.useRef(null),A=d.useRef(null),D=d.useRef(m),U=VC(u),W=VC(o),q=d.useCallback(()=>{if(!M.current||!A.current)return;const N={placement:t,strategy:n,middleware:g};W.current&&(N.platform=W.current),aU(M.current,A.current,N).then(ie=>{const K={...ie,isPositioned:!0};X.current&&!jp(D.current,K)&&(D.current=K,Is.flushSync(()=>{p(K)}))})},[g,t,n,W]);Zh(()=>{f===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(N=>({...N,isPositioned:!1})))},[f]);const X=d.useRef(!1);Zh(()=>(X.current=!0,()=>{X.current=!1}),[]),Zh(()=>{if(R&&(M.current=R),P&&(A.current=P),R&&P){if(U.current)return U.current(R,P,q);q()}},[R,P,q,U]);const ae=d.useMemo(()=>({reference:M,floating:A,setReference:x,setFloating:C}),[x,C]),V=d.useMemo(()=>({reference:R,floating:P}),[R,P]),F=d.useMemo(()=>{const N={position:n,left:0,top:0};if(!V.floating)return N;const ie=UC(V.floating,m.x),K=UC(V.floating,m.y);return l?{...N,transform:"translate("+ie+"px, "+K+"px)",...zT(V.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,V.floating,m.x,m.y]);return d.useMemo(()=>({...m,update:q,refs:ae,elements:V,floatingStyles:F}),[m,q,ae,V,F])}function yx(e){const[t,n]=d.useState(void 0);return An(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,f=Array.isArray(u)?u[0]:u;s=f.inlineSize,l=f.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const BT="Popper",[UT,Fs]=Mn(BT),[uU,VT]=UT(BT),dU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=d.useState(null);return d.createElement(uU,{scope:t,anchor:r,onAnchorChange:o},n)},fU="PopperAnchor",hU=d.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=VT(fU,n),s=d.useRef(null),l=Be(t,s);return d.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:d.createElement(Pe.div,Y({},o,{ref:l}))}),WT="PopperContent",[pU,pte]=UT(WT),mU=d.forwardRef((e,t)=>{var n,r,o,i,s,l,u,f;const{__scopePopper:m,side:p="bottom",sideOffset:g=0,align:y="center",alignOffset:b=0,arrowPadding:S=0,avoidCollisions:E=!0,collisionBoundary:_=[],collisionPadding:x=0,sticky:C="partial",hideWhenDetached:R=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,D=VT(WT,m),[U,W]=d.useState(null),q=Be(t,Kt=>W(Kt)),[X,ae]=d.useState(null),V=yx(X),F=(n=V==null?void 0:V.width)!==null&&n!==void 0?n:0,N=(r=V==null?void 0:V.height)!==null&&r!==void 0?r:0,ie=p+(y!=="center"?"-"+y:""),K=typeof x=="number"?x:{top:0,right:0,bottom:0,left:0,...x},Z=Array.isArray(_)?_:[_],H=Z.length>0,se={padding:K,boundary:Z.filter(gU),altBoundary:H},{refs:ce,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Oe}=cU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>sU(...Kt,{animationFrame:P==="always"}),elements:{reference:D.anchor},middleware:[jB({mainAxis:g+N,alignmentAxis:b}),E&&zB({mainAxis:!0,crossAxis:!1,limiter:C==="partial"?BB():void 0,...se}),E&&IB({...se}),UB({...se,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:Vs})=>{const{width:L,height:Q}=Er.reference,J=Kt.floating.style;J.setProperty("--radix-popper-available-width",`${gt}px`),J.setProperty("--radix-popper-available-height",`${Vs}px`),J.setProperty("--radix-popper-anchor-width",`${L}px`),J.setProperty("--radix-popper-anchor-height",`${Q}px`)}}),X&&lU({element:X,padding:S}),vU({arrowWidth:F,arrowHeight:N}),R&&LB({strategy:"referenceHidden",...se})]}),[he,xe]=HT(Ue),$e=Ft(M);An(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Oe.arrow)===null||o===void 0?void 0:o.x,Me=(i=Oe.arrow)===null||i===void 0?void 0:i.y,je=((s=Oe.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Mt,ct]=d.useState();return An(()=>{U&&ct(window.getComputedStyle(U).zIndex)},[U]),d.createElement("div",{ref:ce.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Mt,"--radix-popper-transform-origin":[(l=Oe.transformOrigin)===null||l===void 0?void 0:l.x,(u=Oe.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},d.createElement(pU,{scope:m,placedSide:he,onArrowChange:ae,arrowX:Ae,arrowY:Me,shouldHideArrow:je},d.createElement(Pe.div,Y({"data-side":he,"data-align":xe},A,{ref:q,style:{...A.style,animation:We?void 0:"none",opacity:(f=Oe.hide)!==null&&f!==void 0&&f.referenceHidden?0:void 0}}))))});function gU(e){return e!==null}const vU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:f}=t,p=((n=f.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=p?0:e.arrowWidth,y=p?0:e.arrowHeight,[b,S]=HT(l),E={start:"0%",center:"50%",end:"100%"}[S],_=((r=(o=f.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,x=((i=(s=f.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let C="",R="";return b==="bottom"?(C=p?E:`${_}px`,R=`${-y}px`):b==="top"?(C=p?E:`${_}px`,R=`${u.floating.height+y}px`):b==="right"?(C=`${-y}px`,R=p?E:`${x}px`):b==="left"&&(C=`${u.floating.width+y}px`,R=p?E:`${x}px`),{data:{x:C,y:R}}}});function HT(e){const[t,n="center"]=e.split("-");return[t,n]}const jd=dU,Vm=hU,Wm=mU,zd=d.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?QI.createPortal(d.createElement(Pe.div,Y({},o,{ref:t})),r):null});function yU(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const Sn=e=>{const{present:t,children:n}=e,r=wU(t),o=typeof n=="function"?n({present:r.isPresent}):d.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?d.cloneElement(o,{ref:i}):null};Sn.displayName="Presence";function wU(e){const[t,n]=d.useState(),r=d.useRef({}),o=d.useRef(e),i=d.useRef("none"),s=e?"mounted":"unmounted",[l,u]=yU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return d.useEffect(()=>{const f=hh(r.current);i.current=l==="mounted"?f:"none"},[l]),An(()=>{const f=r.current,m=o.current;if(m!==e){const g=i.current,y=hh(f);e?u("MOUNT"):y==="none"||(f==null?void 0:f.display)==="none"?u("UNMOUNT"):u(m&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),An(()=>{if(t){const f=p=>{const y=hh(r.current).includes(p.animationName);p.target===t&&y&&Is.flushSync(()=>u("ANIMATION_END"))},m=p=>{p.target===t&&(i.current=hh(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",f),t.addEventListener("animationend",f),()=>{t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",f),t.removeEventListener("animationend",f)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:d.useCallback(f=>{f&&(r.current=getComputedStyle(f)),n(f)},[])}}function hh(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=xU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=d.useCallback(f=>{if(i){const p=typeof f=="function"?f(e):f;p!==e&&l(p)}else o(f)},[i,e,o,l]);return[s,u]}function xU({defaultProp:e,onChange:t}){const n=d.useState(e),[r]=n,o=d.useRef(r),i=Ft(t);return d.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Hm=d.forwardRef((e,t)=>d.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),bU=Hm,[Km,mte]=Mn("Tooltip",[Fs]),wx=Fs(),SU="TooltipProvider",_U=700,d1="tooltip.open",[EU,xx]=Km(SU),CU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=d.useState(!0),u=d.useRef(!1),f=d.useRef(0);return d.useEffect(()=>{const m=f.current;return()=>window.clearTimeout(m)},[]),d.createElement(EU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:d.useCallback(()=>{window.clearTimeout(f.current),l(!1)},[]),onClose:d.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:d.useCallback(m=>{u.current=m},[]),disableHoverableContent:o},i)},bx="Tooltip",[$U,Gm]=Km(bx),RU=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=xx(bx,e.__scopeTooltip),f=wx(t),[m,p]=d.useState(null),g=nr(),y=d.useRef(0),b=s??u.disableHoverableContent,S=l??u.delayDuration,E=d.useRef(!1),[_=!1,x]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(d1))):u.onClose(),i==null||i(A)}}),C=d.useMemo(()=>_?E.current?"delayed-open":"instant-open":"closed",[_]),R=d.useCallback(()=>{window.clearTimeout(y.current),E.current=!1,x(!0)},[x]),P=d.useCallback(()=>{window.clearTimeout(y.current),x(!1)},[x]),M=d.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{E.current=!0,x(!0)},S)},[S,x]);return d.useEffect(()=>()=>window.clearTimeout(y.current),[]),d.createElement(jd,f,d.createElement($U,{scope:t,contentId:g,open:_,stateAttribute:C,trigger:m,onTriggerChange:p,onTriggerEnter:d.useCallback(()=>{u.isOpenDelayed?M():R()},[u.isOpenDelayed,M,R]),onTriggerLeave:d.useCallback(()=>{b?P():window.clearTimeout(y.current)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b},n))},WC="TooltipTrigger",kU=d.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Gm(WC,n),i=xx(WC,n),s=wx(n),l=d.useRef(null),u=Be(t,l,o.onTriggerChange),f=d.useRef(!1),m=d.useRef(!1),p=d.useCallback(()=>f.current=!1,[]);return d.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),d.createElement(Vm,Y({asChild:!0},s),d.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:de(e.onPointerMove,g=>{g.pointerType!=="touch"&&!m.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),m.current=!0)}),onPointerLeave:de(e.onPointerLeave,()=>{o.onTriggerLeave(),m.current=!1}),onPointerDown:de(e.onPointerDown,()=>{f.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:de(e.onFocus,()=>{f.current||o.onOpen()}),onBlur:de(e.onBlur,o.onClose),onClick:de(e.onClick,o.onClose)})))}),TU="TooltipPortal",[gte,PU]=Km(TU,{forceMount:void 0}),ud="TooltipContent",AU=d.forwardRef((e,t)=>{const n=PU(ud,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Gm(ud,e.__scopeTooltip);return d.createElement(Sn,{present:r||s.open},s.disableHoverableContent?d.createElement(KT,Y({side:o},i,{ref:t})):d.createElement(MU,Y({side:o},i,{ref:t})))}),MU=d.forwardRef((e,t)=>{const n=Gm(ud,e.__scopeTooltip),r=xx(ud,e.__scopeTooltip),o=d.useRef(null),i=Be(t,o),[s,l]=d.useState(null),{trigger:u,onClose:f}=n,m=o.current,{onPointerInTransitChange:p}=r,g=d.useCallback(()=>{l(null),p(!1)},[p]),y=d.useCallback((b,S)=>{const E=b.currentTarget,_={x:b.clientX,y:b.clientY},x=NU(_,E.getBoundingClientRect()),C=DU(_,x),R=IU(S.getBoundingClientRect()),P=FU([...C,...R]);l(P),p(!0)},[p]);return d.useEffect(()=>()=>g(),[g]),d.useEffect(()=>{if(u&&m){const b=E=>y(E,m),S=E=>y(E,u);return u.addEventListener("pointerleave",b),m.addEventListener("pointerleave",S),()=>{u.removeEventListener("pointerleave",b),m.removeEventListener("pointerleave",S)}}},[u,m,y,g]),d.useEffect(()=>{if(s){const b=S=>{const E=S.target,_={x:S.clientX,y:S.clientY},x=(u==null?void 0:u.contains(E))||(m==null?void 0:m.contains(E)),C=!LU(_,s);x?g():C&&(g(),f())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,m,s,f,g]),d.createElement(KT,Y({},e,{ref:i}))}),[OU,vte]=Km(bx,{isInside:!1}),KT=d.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Gm(ud,n),f=wx(n),{onClose:m}=u;return d.useEffect(()=>(document.addEventListener(d1,m),()=>document.removeEventListener(d1,m)),[m]),d.useEffect(()=>{if(u.trigger){const p=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&m()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,m]),d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:p=>p.preventDefault(),onDismiss:m},d.createElement(Wm,Y({"data-state":u.stateAttribute},f,l,{ref:t,style:{...l.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)"}}),d.createElement(lx,null,r),d.createElement(OU,{scope:n,isInside:!0},d.createElement(bU,{id:u.contentId,role:"tooltip"},o||r))))});function NU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 DU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function IU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function LU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function FU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),jU(t)}function jU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const zU=CU,BU=RU,UU=kU,GT=AU,VU=zU,YT=BU,XT=UU,Sx=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(GT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));Sx.displayName=GT.displayName;const _x=Dm("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),wn=d.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Zo:"button";return v.jsx(s,{className:Ce(_x({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});wn.displayName="Button";const yn=d.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(wn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(Sx,{children:v.jsx("p",{children:e})})]})),f1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=d.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(yn,{...r,asChild:!0,children:n})}),v.jsx(Ld,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var WU={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"};const HU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=d.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},f)=>d.createElement("svg",{ref:f,...WU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${HU(e)}`,...u},[...t.map(([m,p])=>d.createElement(m,p)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},KU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),GU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),XU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),ZU=Jt("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"}]]),qU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),QU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),JU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),eV=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),ZT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),tV=Jt("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"}]]),nV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),rV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),oV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),iV=Jt("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"}]]),sV=Jt("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"}]]),HC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),KC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),aV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),qT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function lV(e,t){const[n,r]=d.useState(e);return d.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function QT(e){const[t,n]=d.useState(()=>typeof e=="boolean"?e:!!e),r=d.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const _0="focusScope.autoFocusOnMount",E0="focusScope.autoFocusOnUnmount",GC={bubbles:!1,cancelable:!0},Ym=d.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=d.useState(null),f=Ft(o),m=Ft(i),p=d.useRef(null),g=Be(t,S=>u(S)),y=d.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;d.useEffect(()=>{if(r){let x=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?p.current=A:Qi(p.current,{select:!0})},C=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Qi(p.current,{select:!0}))},R=function(M){if(document.activeElement===document.body)for(const D of M)D.removedNodes.length>0&&Qi(l)};var S=x,E=C,_=R;document.addEventListener("focusin",x),document.addEventListener("focusout",C);const P=new MutationObserver(R);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",x),document.removeEventListener("focusout",C),P.disconnect()}}},[r,l,y.paused]),d.useEffect(()=>{if(l){XC.add(y);const S=document.activeElement;if(!l.contains(S)){const _=new CustomEvent(_0,GC);l.addEventListener(_0,f),l.dispatchEvent(_),_.defaultPrevented||(cV(pV(JT(l)),{select:!0}),document.activeElement===S&&Qi(l))}return()=>{l.removeEventListener(_0,f),setTimeout(()=>{const _=new CustomEvent(E0,GC);l.addEventListener(E0,m),l.dispatchEvent(_),_.defaultPrevented||Qi(S??document.body,{select:!0}),l.removeEventListener(E0,m),XC.remove(y)},0)}}},[l,f,m,y]);const b=d.useCallback(S=>{if(!n&&!r||y.paused)return;const E=S.key==="Tab"&&!S.altKey&&!S.ctrlKey&&!S.metaKey,_=document.activeElement;if(E&&_){const x=S.currentTarget,[C,R]=uV(x);C&&R?!S.shiftKey&&_===R?(S.preventDefault(),n&&Qi(C,{select:!0})):S.shiftKey&&_===C&&(S.preventDefault(),n&&Qi(R,{select:!0})):_===x&&S.preventDefault()}},[n,r,y.paused]);return d.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:b}))});function cV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Qi(r,{select:t}),document.activeElement!==n)return}function uV(e){const t=JT(e),n=YC(t,e),r=YC(t.reverse(),e);return[n,r]}function JT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function YC(e,t){for(const n of e)if(!dV(n,{upTo:t}))return n}function dV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function fV(e){return e instanceof HTMLInputElement&&"select"in e}function Qi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&fV(e)&&t&&e.select()}}const XC=hV();function hV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=ZC(e,t),e.unshift(t)},remove(t){var n;e=ZC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function ZC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let C0=0;function Xm(){d.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:qC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:qC()),C0++,()=>{C0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),C0--}},[])}function qC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Lo=function(){return Lo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return AV;var t=MV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},NV=rP(),DV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(gV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(qh,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Qh,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(qh," .").concat(qh,` { + right: 0 `).concat(r,`; + } + + .`).concat(Qh," .").concat(Qh,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(vV,": ").concat(l,`px; + } +`)},IV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=d.useMemo(function(){return OV(o)},[o]);return d.createElement(NV,{styles:DV(i,!t,o,n?"":"!important")})},h1=!1;if(typeof window<"u")try{var ph=Object.defineProperty({},"passive",{get:function(){return h1=!0,!0}});window.addEventListener("test",ph,ph),window.removeEventListener("test",ph,ph)}catch{h1=!1}var rl=h1?{passive:!1}:!1,LV=function(e){return e.tagName==="TEXTAREA"},oP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!LV(e)&&n[t]==="visible")},FV=function(e){return oP(e,"overflowY")},jV=function(e){return oP(e,"overflowX")},JC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=iP(e,n);if(r){var o=sP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},zV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},BV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},iP=function(e,t){return e==="v"?FV(t):jV(t)},sP=function(e,t){return e==="v"?zV(t):BV(t)},UV=function(e,t){return e==="h"&&t==="rtl"?-1:1},VV=function(e,t,n,r,o){var i=UV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),f=!1,m=s>0,p=0,g=0;do{var y=sP(e,l),b=y[0],S=y[1],E=y[2],_=S-E-i*b;(b||_)&&iP(e,l)&&(p+=_,g+=b),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(m&&(o&&p===0||!o&&s>p)||!m&&(o&&g===0||!o&&-s>g))&&(f=!0),f},mh=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},e2=function(e){return[e.deltaX,e.deltaY]},t2=function(e){return e&&"current"in e?e.current:e},WV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},HV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},KV=0,ol=[];function GV(e){var t=d.useRef([]),n=d.useRef([0,0]),r=d.useRef(),o=d.useState(KV++)[0],i=d.useState(function(){return rP()})[0],s=d.useRef(e);d.useEffect(function(){s.current=e},[e]),d.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var S=mV([e.lockRef.current],(e.shards||[]).map(t2),!0).filter(Boolean);return S.forEach(function(E){return E.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),S.forEach(function(E){return E.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=d.useCallback(function(S,E){if("touches"in S&&S.touches.length===2)return!s.current.allowPinchZoom;var _=mh(S),x=n.current,C="deltaX"in S?S.deltaX:x[0]-_[0],R="deltaY"in S?S.deltaY:x[1]-_[1],P,M=S.target,A=Math.abs(C)>Math.abs(R)?"h":"v";if("touches"in S&&A==="h"&&M.type==="range")return!1;var D=JC(A,M);if(!D)return!0;if(D?P=A:(P=A==="v"?"h":"v",D=JC(A,M)),!D)return!1;if(!r.current&&"changedTouches"in S&&(C||R)&&(r.current=P),!P)return!0;var U=r.current||P;return VV(U,E,S,U==="h"?C:R,!0)},[]),u=d.useCallback(function(S){var E=S;if(!(!ol.length||ol[ol.length-1]!==i)){var _="deltaY"in E?e2(E):mh(E),x=t.current.filter(function(P){return P.name===E.type&&P.target===E.target&&WV(P.delta,_)})[0];if(x&&x.should){E.cancelable&&E.preventDefault();return}if(!x){var C=(s.current.shards||[]).map(t2).filter(Boolean).filter(function(P){return P.contains(E.target)}),R=C.length>0?l(E,C[0]):!s.current.noIsolation;R&&E.cancelable&&E.preventDefault()}}},[]),f=d.useCallback(function(S,E,_,x){var C={name:S,delta:E,target:_,should:x};t.current.push(C),setTimeout(function(){t.current=t.current.filter(function(R){return R!==C})},1)},[]),m=d.useCallback(function(S){n.current=mh(S),r.current=void 0},[]),p=d.useCallback(function(S){f(S.type,e2(S),S.target,l(S,e.lockRef.current))},[]),g=d.useCallback(function(S){f(S.type,mh(S),S.target,l(S,e.lockRef.current))},[]);d.useEffect(function(){return ol.push(i),e.setCallbacks({onScrollCapture:p,onWheelCapture:p,onTouchMoveCapture:g}),document.addEventListener("wheel",u,rl),document.addEventListener("touchmove",u,rl),document.addEventListener("touchstart",m,rl),function(){ol=ol.filter(function(S){return S!==i}),document.removeEventListener("wheel",u,rl),document.removeEventListener("touchmove",u,rl),document.removeEventListener("touchstart",m,rl)}},[]);var y=e.removeScrollBar,b=e.inert;return d.createElement(d.Fragment,null,b?d.createElement(i,{styles:HV(o)}):null,y?d.createElement(IV,{gapMode:"margin"}):null)}const YV=EV(nP,GV);var aP=d.forwardRef(function(e,t){return d.createElement(Zm,Lo({},e,{ref:t,sideCar:YV}))});aP.classNames=Zm.classNames;const qm=aP;var XV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},il=new WeakMap,gh=new WeakMap,vh={},k0=0,lP=function(e){return e&&(e.host||lP(e.parentNode))},ZV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=lP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},qV=function(e,t,n,r){var o=ZV(t,Array.isArray(e)?e:[e]);vh[n]||(vh[n]=new WeakMap);var i=vh[n],s=[],l=new Set,u=new Set(o),f=function(p){!p||l.has(p)||(l.add(p),f(p.parentNode))};o.forEach(f);var m=function(p){!p||u.has(p)||Array.prototype.forEach.call(p.children,function(g){if(l.has(g))m(g);else{var y=g.getAttribute(r),b=y!==null&&y!=="false",S=(il.get(g)||0)+1,E=(i.get(g)||0)+1;il.set(g,S),i.set(g,E),s.push(g),S===1&&b&&gh.set(g,!0),E===1&&g.setAttribute(n,"true"),b||g.setAttribute(r,"true")}})};return m(t),l.clear(),k0++,function(){s.forEach(function(p){var g=il.get(p)-1,y=i.get(p)-1;il.set(p,g),i.set(p,y),g||(gh.has(p)||p.removeAttribute(r),gh.delete(p)),y||p.removeAttribute(n)}),k0--,k0||(il=new WeakMap,il=new WeakMap,gh=new WeakMap,vh={})}},Qm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||XV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),qV(r,o,n,"aria-hidden")):function(){return null}};const cP="Dialog",[uP,dP]=Mn(cP),[QV,Eo]=uP(cP),JV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=d.useRef(null),u=d.useRef(null),[f=!1,m]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(QV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:f,onOpenChange:m,onOpenToggle:d.useCallback(()=>m(p=>!p),[m]),modal:s},n)},eW="DialogTrigger",fP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(eW,n),i=Be(t,o.triggerRef);return d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":Ex(o.open)},r,{ref:i,onClick:de(e.onClick,o.onOpenToggle)}))}),hP="DialogPortal",[tW,pP]=uP(hP,{forceMount:void 0}),nW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=Eo(hP,t);return d.createElement(tW,{scope:t,forceMount:n},d.Children.map(r,s=>d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},s))))},p1="DialogOverlay",rW=d.forwardRef((e,t)=>{const n=pP(p1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(p1,e.__scopeDialog);return i.modal?d.createElement(Sn,{present:r||i.open},d.createElement(oW,Y({},o,{ref:t}))):null}),oW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(p1,n);return d.createElement(qm,{as:Zo,allowPinchZoom:!0,shards:[o.contentRef]},d.createElement(Pe.div,Y({"data-state":Ex(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),uc="DialogContent",iW=d.forwardRef((e,t)=>{const n=pP(uc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=Eo(uc,e.__scopeDialog);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(sW,Y({},o,{ref:t})):d.createElement(aW,Y({},o,{ref:t})))}),sW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(null),o=Be(t,n.contentRef,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(mP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault())}))}),aW=d.forwardRef((e,t)=>{const n=Eo(uc,e.__scopeDialog),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(mP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),mP=d.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=Eo(uc,n),u=d.useRef(null),f=Be(t,u);return Xm(),d.createElement(d.Fragment,null,d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":Ex(l.open)},s,{ref:f,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),gP="DialogTitle",lW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(gP,n);return d.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),cW="DialogDescription",vP=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(cW,n);return d.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),uW="DialogClose",dW=d.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=Eo(uW,n);return d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,()=>o.onOpenChange(!1))}))});function Ex(e){return e?"open":"closed"}const fW="DialogTitleWarning",[hW,yte]=pB(fW,{contentName:uc,titleName:gP,docsSlug:"dialog"}),Cx=JV,yP=fP,$x=nW,Bd=rW,Ud=iW,Vd=lW,Wd=vP,Rx=dW,Jm=Cx,kx=yP,pW=$x,wP=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));wP.displayName=Bd.displayName;const Hd=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(wP,{}),v.jsxs(Ud,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Rx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(wT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Hd.displayName=Ud.displayName;const xP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});xP.displayName="DialogHeader";const Kd=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));Kd.displayName=Vd.displayName;const mW=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));mW.displayName=Wd.displayName;function m1(){return m1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,f=n.keys,m=t.key,p=t.code,g=t.ctrlKey,y=t.metaKey,b=t.shiftKey,S=t.altKey,E=hs(p),_=m.toLowerCase();if(!r){if(o===!S&&_!=="alt"||l===!b&&_!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&_!=="meta"&&_!=="os"||u===!g&&_!=="ctrl"&&_!=="control")return!1}return f&&f.length===1&&(f.includes(_)||f.includes(E))?!0:f?yW(f):!f},EW=d.createContext(void 0),CW=function(){return d.useContext(EW)};function CP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&CP(e[r],t[r])},!0):e===t}var $W=d.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),RW=function(){return d.useContext($W)};function kW(e){var t=d.useRef(void 0);return CP(t.current,e)||(t.current=e),t.current}var n2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},TW=typeof window<"u"?d.useLayoutEffect:d.useEffect;function PW(e,t,n,r){var o=d.useRef(null),i=d.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=Tx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,f=d.useCallback(t,u??[]),m=d.useRef(f);u?m.current=f:m.current=t;var p=kW(s),g=RW(),y=g.enabledScopes,b=CW();return TW(function(){if(!((p==null?void 0:p.enabled)===!1||!SW(y,p==null?void 0:p.scopes))){var S=function(R,P){var M;if(P===void 0&&(P=!1),!(bW(R)&&!EP(R,p==null?void 0:p.enableOnFormTags))&&!(p!=null&&p.ignoreEventWhen!=null&&p.ignoreEventWhen(R))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){n2(R);return}(M=R.target)!=null&&M.isContentEditable&&!(p!=null&&p.enableOnContentEditable)||T0(l,p==null?void 0:p.splitKey).forEach(function(A){var D,U=P0(A,p==null?void 0:p.combinationKey);if(_W(R,U,p==null?void 0:p.ignoreModifiers)||(D=U.keys)!=null&&D.includes("*")){if(P&&i.current)return;if(wW(R,U,p==null?void 0:p.preventDefault),!xW(R,U,p==null?void 0:p.enabled)){n2(R);return}m.current(R,U),P||(i.current=!0)}})}},E=function(R){R.key!==void 0&&(SP(hs(R.code)),((p==null?void 0:p.keydown)===void 0&&(p==null?void 0:p.keyup)!==!0||p!=null&&p.keydown)&&S(R))},_=function(R){R.key!==void 0&&(_P(hs(R.code)),i.current=!1,p!=null&&p.keyup&&S(R,!0))},x=o.current||(s==null?void 0:s.document)||document;return x.addEventListener("keyup",_),x.addEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.addHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))}),function(){x.removeEventListener("keyup",_),x.removeEventListener("keydown",E),b&&T0(l,p==null?void 0:p.splitKey).forEach(function(C){return b.removeHotkey(P0(C,p==null?void 0:p.combinationKey,p==null?void 0:p.description))})}}},[l,p,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return PW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const AW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},yh=()=>AW()?"Cmd":"Ctrl";function MW(){const[e,t]=QT(!1);return Zn("h",()=>{t()}),v.jsxs(Jm,{open:e,onOpenChange:t,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Hotkeys",children:v.jsx(nV,{})})}),v.jsx(Hd,{children:v.jsxs(xP,{children:[v.jsx(Kd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[yh(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[yh(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[yh(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[yh(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Px(e){const[t]=d.useState(new Image),[n,r]=d.useState(!1);return d.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const $P="Popover",[RP,wte]=Mn($P,[Fs]),Ax=Fs(),[OW,Rc]=RP($P),NW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Ax(t),u=d.useRef(null),[f,m]=d.useState(!1),[p=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(jd,l,d.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:p,onOpenChange:g,onOpenToggle:d.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:f,onCustomAnchorAdd:d.useCallback(()=>m(!0),[]),onCustomAnchorRemove:d.useCallback(()=>m(!1),[]),modal:s},n))},DW="PopoverTrigger",IW=d.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=Rc(DW,n),i=Ax(n),s=Be(t,o.triggerRef),l=d.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":PP(o.open)},r,{ref:s,onClick:de(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:d.createElement(Vm,Y({asChild:!0},i),l)}),kP="PopoverPortal",[LW,FW]=RP(kP,{forceMount:void 0}),jW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=Rc(kP,t);return d.createElement(LW,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},dd="PopoverContent",zW=d.forwardRef((e,t)=>{const n=FW(dd,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=Rc(dd,e.__scopePopover);return d.createElement(Sn,{present:r||i.open},i.modal?d.createElement(BW,Y({},o,{ref:t})):d.createElement(UW,Y({},o,{ref:t})))}),BW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(null),o=Be(t,r),i=d.useRef(!1);return d.useEffect(()=>{const s=r.current;if(s)return Qm(s)},[]),d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(TP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:de(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:de(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,f=l.button===2||u;i.current=f},{checkForDefaultPrevented:!1}),onFocusOutside:de(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),UW=d.forwardRef((e,t)=>{const n=Rc(dd,e.__scopePopover),r=d.useRef(!1),o=d.useRef(!1);return d.createElement(TP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),TP=d.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onInteractOutside:m,...p}=e,g=Rc(dd,n),y=Ax(n);return Xm(),d.createElement(Ym,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:m,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:f,onDismiss:()=>g.onOpenChange(!1)},d.createElement(Wm,Y({"data-state":PP(g.open),role:"dialog",id:g.contentId},y,p,{ref:t,style:{...p.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)"}}))))});function PP(e){return e?"open":"closed"}const VW=NW,WW=IW,HW=jW,AP=zW,KW=VW,GW=WW,MP=d.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(HW,{children:v.jsx(AP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));MP.displayName=AP.displayName;function YW(){var e=d.useRef(!0);return e.current?(e.current=!1,!0):e.current}var XW=function(e,t){var n=YW();d.useEffect(function(){if(!n)return e()},t)};const ZW=XW;var qW=function(){};function Mx(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=d.useRef(null);NP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},f=g=>{g.key==="Enter"&&!e&&u()},m=()=>{o()},p=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Ld,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:f,placeholder:"I want to repaint of..."}),v.jsx(wn,{size:"sm",onClick:u,disabled:e,onMouseEnter:m,onMouseLeave:p,children:"Paint"})]})};var zp={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */zp.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",f=500,m="__lodash_placeholder__",p=1,g=2,y=4,b=1,S=2,E=1,_=2,x=4,C=8,R=16,P=32,M=64,A=128,D=256,U=512,W=30,q="...",X=800,ae=16,V=1,F=2,N=3,ie=1/0,K=9007199254740991,Z=17976931348623157e292,H=NaN,se=4294967295,ce=se-1,Ve=se>>>1,Ue=[["ary",A],["bind",E],["bindKey",_],["curry",C],["curryRight",R],["flip",U],["partial",P],["partialRight",M],["rearg",D]],We="[object Arguments]",Oe="[object Array]",he="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Me="[object Error]",je="[object Function]",Mt="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",Vs="[object Promise]",L="[object Proxy]",Q="[object RegExp]",J="[object Set]",we="[object String]",me="[object Symbol]",fe="[object Undefined]",Re="[object WeakMap]",ft="[object WeakSet]",ht="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",Ni="[object Float64Array]",Co="[object Int8Array]",Vn="[object Int16Array]",Ba="[object Int32Array]",Di="[object Uint8Array]",Ws="[object Uint8ClampedArray]",Ii="[object Uint16Array]",Mc="[object Uint32Array]",bg=/\b__p \+= '';/g,Sg=/\b(__p \+=) '' \+/g,Jd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Oc=/&(?:amp|lt|gt|quot|#39);/g,Nc=/[&<>"']/g,Dc=RegExp(Oc.source),_g=RegExp(Nc.source),Ic=/<%-([\s\S]+?)%>/g,ef=/<%([\s\S]+?)%>/g,Lc=/<%=([\s\S]+?)%>/g,Eg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Cg=/^\w*$/,$g=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,G=/[\\^$.*+?()[\]{}|]/g,Ye=RegExp(G.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,tf=/\{\n\/\* \[wrapped with (.+)\] \*/,aM=/,? & /,lM=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,cM=/[()=,{}\[\]\/\s]/,uM=/\\(\\)?/g,dM=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,hb=/\w*$/,fM=/^[-+]0x[0-9a-f]+$/i,hM=/^0b[01]+$/i,pM=/^\[object .+?Constructor\]$/,mM=/^0o[0-7]+$/i,gM=/^(?:0|[1-9]\d*)$/,vM=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,nf=/($^)/,yM=/['\n\r\u2028\u2029\\]/g,rf="\\ud800-\\udfff",wM="\\u0300-\\u036f",xM="\\ufe20-\\ufe2f",bM="\\u20d0-\\u20ff",pb=wM+xM+bM,mb="\\u2700-\\u27bf",gb="a-z\\xdf-\\xf6\\xf8-\\xff",SM="\\xac\\xb1\\xd7\\xf7",_M="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",EM="\\u2000-\\u206f",CM=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",vb="A-Z\\xc0-\\xd6\\xd8-\\xde",yb="\\ufe0e\\ufe0f",wb=SM+_M+EM+CM,Rg="['’]",$M="["+rf+"]",xb="["+wb+"]",of="["+pb+"]",bb="\\d+",RM="["+mb+"]",Sb="["+gb+"]",_b="[^"+rf+wb+bb+mb+gb+vb+"]",kg="\\ud83c[\\udffb-\\udfff]",kM="(?:"+of+"|"+kg+")",Eb="[^"+rf+"]",Tg="(?:\\ud83c[\\udde6-\\uddff]){2}",Pg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ua="["+vb+"]",Cb="\\u200d",$b="(?:"+Sb+"|"+_b+")",TM="(?:"+Ua+"|"+_b+")",Rb="(?:"+Rg+"(?:d|ll|m|re|s|t|ve))?",kb="(?:"+Rg+"(?:D|LL|M|RE|S|T|VE))?",Tb=kM+"?",Pb="["+yb+"]?",PM="(?:"+Cb+"(?:"+[Eb,Tg,Pg].join("|")+")"+Pb+Tb+")*",AM="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",MM="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Ab=Pb+Tb+PM,OM="(?:"+[RM,Tg,Pg].join("|")+")"+Ab,NM="(?:"+[Eb+of+"?",of,Tg,Pg,$M].join("|")+")",DM=RegExp(Rg,"g"),IM=RegExp(of,"g"),Ag=RegExp(kg+"(?="+kg+")|"+NM+Ab,"g"),LM=RegExp([Ua+"?"+Sb+"+"+Rb+"(?="+[xb,Ua,"$"].join("|")+")",TM+"+"+kb+"(?="+[xb,Ua+$b,"$"].join("|")+")",Ua+"?"+$b+"+"+Rb,Ua+"+"+kb,MM,AM,bb,OM].join("|"),"g"),FM=RegExp("["+Cb+rf+pb+yb+"]"),jM=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,zM=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],BM=-1,Rt={};Rt[Cr]=Rt[Ni]=Rt[Co]=Rt[Vn]=Rt[Ba]=Rt[Di]=Rt[Ws]=Rt[Ii]=Rt[Mc]=!0,Rt[We]=Rt[Oe]=Rt[ht]=Rt[xe]=Rt[_n]=Rt[$e]=Rt[Me]=Rt[je]=Rt[ct]=Rt[Kt]=Rt[gt]=Rt[Q]=Rt[J]=Rt[we]=Rt[Re]=!1;var Et={};Et[We]=Et[Oe]=Et[ht]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[Ni]=Et[Co]=Et[Vn]=Et[Ba]=Et[ct]=Et[Kt]=Et[gt]=Et[Q]=Et[J]=Et[we]=Et[me]=Et[Di]=Et[Ws]=Et[Ii]=Et[Mc]=!0,Et[Me]=Et[je]=Et[Re]=!1;var UM={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},VM={"&":"&","<":"<",">":">",'"':""","'":"'"},WM={"&":"&","<":"<",">":">",""":'"',"'":"'"},HM={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},KM=parseFloat,GM=parseInt,Mb=typeof Jc=="object"&&Jc&&Jc.Object===Object&&Jc,YM=typeof self=="object"&&self&&self.Object===Object&&self,fn=Mb||YM||Function("return this")(),Mg=t&&!t.nodeType&&t,Hs=Mg&&!0&&e&&!e.nodeType&&e,Ob=Hs&&Hs.exports===Mg,Og=Ob&&Mb.process,$r=function(){try{var j=Hs&&Hs.require&&Hs.require("util").types;return j||Og&&Og.binding&&Og.binding("util")}catch{}}(),Nb=$r&&$r.isArrayBuffer,Db=$r&&$r.isDate,Ib=$r&&$r.isMap,Lb=$r&&$r.isRegExp,Fb=$r&&$r.isSet,jb=$r&&$r.isTypedArray;function or(j,te,ee){switch(ee.length){case 0:return j.call(te);case 1:return j.call(te,ee[0]);case 2:return j.call(te,ee[0],ee[1]);case 3:return j.call(te,ee[0],ee[1],ee[2])}return j.apply(te,ee)}function XM(j,te,ee,Se){for(var Ke=-1,pt=j==null?0:j.length;++Ke-1}function Ng(j,te,ee){for(var Se=-1,Ke=j==null?0:j.length;++Se-1;);return ee}function Gb(j,te){for(var ee=j.length;ee--&&Va(te,j[ee],0)>-1;);return ee}function oO(j,te){for(var ee=j.length,Se=0;ee--;)j[ee]===te&&++Se;return Se}var iO=Fg(UM),sO=Fg(VM);function aO(j){return"\\"+HM[j]}function lO(j,te){return j==null?n:j[te]}function Wa(j){return FM.test(j)}function cO(j){return jM.test(j)}function uO(j){for(var te,ee=[];!(te=j.next()).done;)ee.push(te.value);return ee}function Ug(j){var te=-1,ee=Array(j.size);return j.forEach(function(Se,Ke){ee[++te]=[Ke,Se]}),ee}function Yb(j,te){return function(ee){return j(te(ee))}}function ji(j,te){for(var ee=-1,Se=j.length,Ke=0,pt=[];++ee-1}function qO(a,c){var h=this.__data__,w=_f(h,a);return w<0?(++this.size,h.push([a,c])):h[w][1]=c,this}ti.prototype.clear=GO,ti.prototype.delete=YO,ti.prototype.get=XO,ti.prototype.has=ZO,ti.prototype.set=qO;function ni(a){var c=-1,h=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,h,w,$,T){var O,I=c&p,B=c&g,ne=c&y;if(h&&(O=$?h(a,w,$,T):h(a)),O!==n)return O;if(!It(a))return a;var re=Ge(a);if(re){if(O=tN(a),!I)return Wn(a,O)}else{var le=Cn(a),ge=le==je||le==Mt;if(Hi(a))return PS(a,I);if(le==gt||le==We||ge&&!$){if(O=B||ge?{}:XS(a),!I)return B?W6(a,h6(O,a)):V6(a,sS(O,a))}else{if(!Et[le])return $?a:{};O=nN(a,le,I)}}T||(T=new eo);var ke=T.get(a);if(ke)return ke;T.set(a,O),E_(a)?a.forEach(function(Le){O.add(Pr(Le,c,h,Le,a,T))}):S_(a)&&a.forEach(function(Le,nt){O.set(nt,Pr(Le,c,h,nt,a,T))});var Ie=ne?B?pv:hv:B?Kn:ln,Qe=re?n:Ie(a);return Rr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Wc(O,nt,Pr(Le,c,h,nt,a,T))}),O}function p6(a){var c=ln(a);return function(h){return aS(h,a,c)}}function aS(a,c,h){var w=h.length;if(a==null)return!w;for(a=St(a);w--;){var $=h[w],T=c[$],O=a[$];if(O===n&&!($ in a)||!T(O))return!1}return!0}function lS(a,c,h){if(typeof a!="function")throw new kr(s);return qc(function(){a.apply(n,h)},c)}function Hc(a,c,h,w){var $=-1,T=sf,O=!0,I=a.length,B=[],ne=c.length;if(!I)return B;h&&(c=Ot(c,ir(h))),w?(T=Ng,O=!1):c.length>=o&&(T=Fc,O=!1,c=new Ys(c));e:for(;++$$?0:$+h),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=h>w?0:$_(w);h0&&h(I)?c>1?hn(I,c-1,h,w,$):Fi($,I):w||($[$.length]=I)}return $}var Xg=IS(),dS=IS(!0);function $o(a,c){return a&&Xg(a,c,ln)}function Zg(a,c){return a&&dS(a,c,ln)}function Cf(a,c){return Li(c,function(h){return ai(a[h])})}function Zs(a,c){c=Vi(c,a);for(var h=0,w=c.length;a!=null&&hc}function v6(a,c){return a!=null&&yt.call(a,c)}function y6(a,c){return a!=null&&c in St(a)}function w6(a,c,h){return a>=En(c,h)&&a=120&&re.length>=120)?new Ys(O&&re):n}re=a[0];var le=-1,ge=I[0];e:for(;++le<$&&ne.length-1;)I!==a&&gf.call(I,B,1),gf.call(a,B,1);return a}function SS(a,c){for(var h=a?c.length:0,w=h-1;h--;){var $=c[h];if(h==w||$!==T){var T=$;si($)?gf.call(a,$,1):sv(a,$)}}return a}function rv(a,c){return a+wf(nS()*(c-a+1))}function M6(a,c,h,w){for(var $=-1,T=tn(yf((c-a)/(h||1)),0),O=ee(T);T--;)O[w?T:++$]=a,a+=h;return O}function ov(a,c){var h="";if(!a||c<1||c>K)return h;do c%2&&(h+=a),c=wf(c/2),c&&(a+=a);while(c);return h}function et(a,c){return bv(QS(a,c,Gn),a+"")}function O6(a){return iS(tl(a))}function N6(a,c){var h=tl(a);return If(h,Xs(c,0,h.length))}function Yc(a,c,h,w){if(!It(a))return a;c=Vi(c,a);for(var $=-1,T=c.length,O=T-1,I=a;I!=null&&++$$?0:$+c),h=h>$?$:h,h<0&&(h+=$),$=c>h?0:h-c>>>0,c>>>=0;for(var T=ee($);++w<$;)T[w]=a[w+c];return T}function L6(a,c){var h;return Bi(a,function(w,$,T){return h=c(w,$,T),!h}),!!h}function Rf(a,c,h){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,O=a[T];O!==null&&!ar(O)&&(h?O<=c:O=o){var ne=c?null:Y6(a);if(ne)return lf(ne);O=!1,$=Fc,B=new Ys}else B=c?[]:I;e:for(;++w=w?a:Ar(a,c,h)}var TS=CO||function(a){return fn.clearTimeout(a)};function PS(a,c){if(c)return a.slice();var h=a.length,w=qb?qb(h):new a.constructor(h);return a.copy(w),w}function uv(a){var c=new a.constructor(a.byteLength);return new pf(c).set(new pf(a)),c}function j6(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.byteLength)}function z6(a){var c=new a.constructor(a.source,hb.exec(a));return c.lastIndex=a.lastIndex,c}function B6(a){return Vc?St(Vc.call(a)):{}}function AS(a,c){var h=c?uv(a.buffer):a.buffer;return new a.constructor(h,a.byteOffset,a.length)}function MS(a,c){if(a!==c){var h=a!==n,w=a===null,$=a===a,T=ar(a),O=c!==n,I=c===null,B=c===c,ne=ar(c);if(!I&&!ne&&!T&&a>c||T&&O&&B&&!I&&!ne||w&&O&&B||!h&&B||!$)return 1;if(!w&&!T&&!ne&&a=I)return B;var ne=h[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function OS(a,c,h,w){for(var $=-1,T=a.length,O=h.length,I=-1,B=c.length,ne=tn(T-O,0),re=ee(B+ne),le=!w;++I1?h[$-1]:n,O=$>2?h[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,O&&Nn(h[0],h[1],O)&&(T=$<3?n:T,$=1),c=St(c);++w<$;){var I=h[w];I&&a(c,I,w,T)}return c})}function DS(a,c){return function(h,w){if(h==null)return h;if(!Hn(h))return a(h,w);for(var $=h.length,T=c?$:-1,O=St(h);(c?T--:++T<$)&&w(O[T],T,O)!==!1;);return h}}function IS(a){return function(c,h,w){for(var $=-1,T=St(c),O=w(c),I=O.length;I--;){var B=O[a?I:++$];if(h(T[B],B,T)===!1)break}return c}}function H6(a,c,h){var w=c&E,$=Xc(a);function T(){var O=this&&this!==fn&&this instanceof T?$:a;return O.apply(w?h:this,arguments)}return T}function LS(a){return function(c){c=vt(c);var h=Wa(c)?Jr(c):n,w=h?h[0]:c.charAt(0),$=h?Wi(h,1).join(""):c.slice(1);return w[a]()+$}}function Qa(a){return function(c){return Dg(D_(N_(c).replace(DM,"")),a,"")}}function Xc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var h=Za(a.prototype),w=a.apply(h,c);return It(w)?w:h}}function K6(a,c,h){var w=Xc(a);function $(){for(var T=arguments.length,O=ee(T),I=T,B=Ja($);I--;)O[I]=arguments[I];var ne=T<3&&O[0]!==B&&O[T-1]!==B?[]:ji(O,B);if(T-=ne.length,T-1?$[T?c[O]:O]:n}}function jS(a){return ii(function(c){var h=c.length,w=h,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new kr(s);if($&&!O&&Nf(T)=="wrapper")var O=new Tr([],!0)}for(w=O?w:h;++w1&&at.reverse(),re&&BI))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var le=-1,ge=!0,ke=h&S?new Ys:n;for(T.set(a,c),T.set(c,a);++le1?"& ":"")+c[w],c=c.join(h>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function oN(a){return Ge(a)||Js(a)||!!(eS&&a&&a[eS])}function si(a,c){var h=typeof a;return c=c??K,!!c&&(h=="number"||h!="symbol"&&gM.test(a))&&a>-1&&a%1==0&&a0){if(++c>=X)return arguments[0]}else c=0;return a.apply(n,arguments)}}function If(a,c){var h=-1,w=a.length,$=w-1;for(c=c===n?w:c;++h1?a[c-1]:n;return h=typeof h=="function"?(a.pop(),h):n,u_(a,h)});function d_(a){var c=k(a);return c.__chain__=!0,c}function m7(a,c){return c(a),a}function Lf(a,c){return c(a)}var g7=ii(function(a){var c=a.length,h=c?a[0]:0,w=this.__wrapped__,$=function(T){return Yg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!si(h)?this.thru($):(w=w.slice(h,+h+(c?1:0)),w.__actions__.push({func:Lf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function v7(){return d_(this)}function y7(){return new Tr(this.value(),this.__chain__)}function w7(){this.__values__===n&&(this.__values__=C_(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function x7(){return this}function b7(a){for(var c,h=this;h instanceof Sf;){var w=o_(h);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;h=h.__wrapped__}return $.__wrapped__=a,c}function S7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Lf,args:[Sv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(Sv)}function _7(){return RS(this.__wrapped__,this.__actions__)}var E7=Tf(function(a,c,h){yt.call(a,h)?++a[h]:ri(a,h,1)});function C7(a,c,h){var w=Ge(a)?zb:m6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}function $7(a,c){var h=Ge(a)?Li:uS;return h(a,De(c,3))}var R7=FS(i_),k7=FS(s_);function T7(a,c){return hn(Ff(a,c),1)}function P7(a,c){return hn(Ff(a,c),ie)}function A7(a,c,h){return h=h===n?1:qe(h),hn(Ff(a,c),h)}function f_(a,c){var h=Ge(a)?Rr:Bi;return h(a,De(c,3))}function h_(a,c){var h=Ge(a)?ZM:cS;return h(a,De(c,3))}var M7=Tf(function(a,c,h){yt.call(a,h)?a[h].push(c):ri(a,h,[c])});function O7(a,c,h,w){a=Hn(a)?a:tl(a),h=h&&!w?qe(h):0;var $=a.length;return h<0&&(h=tn($+h,0)),Vf(a)?h<=$&&a.indexOf(c,h)>-1:!!$&&Va(a,c,h)>-1}var N7=et(function(a,c,h){var w=-1,$=typeof c=="function",T=Hn(a)?ee(a.length):[];return Bi(a,function(O){T[++w]=$?or(c,O,h):Kc(O,c,h)}),T}),D7=Tf(function(a,c,h){ri(a,h,c)});function Ff(a,c){var h=Ge(a)?Ot:gS;return h(a,De(c,3))}function I7(a,c,h,w){return a==null?[]:(Ge(c)||(c=c==null?[]:[c]),h=w?n:h,Ge(h)||(h=h==null?[]:[h]),xS(a,c,h))}var L7=Tf(function(a,c,h){a[h?0:1].push(c)},function(){return[[],[]]});function F7(a,c,h){var w=Ge(a)?Dg:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,Bi)}function j7(a,c,h){var w=Ge(a)?qM:Wb,$=arguments.length<3;return w(a,De(c,4),h,$,cS)}function z7(a,c){var h=Ge(a)?Li:uS;return h(a,Bf(De(c,3)))}function B7(a){var c=Ge(a)?iS:O6;return c(a)}function U7(a,c,h){(h?Nn(a,c,h):c===n)?c=1:c=qe(c);var w=Ge(a)?u6:N6;return w(a,c)}function V7(a){var c=Ge(a)?d6:I6;return c(a)}function W7(a){if(a==null)return 0;if(Hn(a))return Vf(a)?Ha(a):a.length;var c=Cn(a);return c==ct||c==J?a.size:ev(a).length}function H7(a,c,h){var w=Ge(a)?Ig:L6;return h&&Nn(a,c,h)&&(c=n),w(a,De(c,3))}var K7=et(function(a,c){if(a==null)return[];var h=c.length;return h>1&&Nn(a,c[0],c[1])?c=[]:h>2&&Nn(c[0],c[1],c[2])&&(c=[c[0]]),xS(a,hn(c,1),[])}),jf=$O||function(){return fn.Date.now()};function G7(a,c){if(typeof c!="function")throw new kr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function p_(a,c,h){return c=h?n:c,c=a&&c==null?a.length:c,oi(a,A,n,n,n,n,c)}function m_(a,c){var h;if(typeof c!="function")throw new kr(s);return a=qe(a),function(){return--a>0&&(h=c.apply(this,arguments)),a<=1&&(c=n),h}}var Ev=et(function(a,c,h){var w=E;if(h.length){var $=ji(h,Ja(Ev));w|=P}return oi(a,w,c,h,$)}),g_=et(function(a,c,h){var w=E|_;if(h.length){var $=ji(h,Ja(g_));w|=P}return oi(c,w,a,h,$)});function v_(a,c,h){c=h?n:c;var w=oi(a,C,n,n,n,n,n,c);return w.placeholder=v_.placeholder,w}function y_(a,c,h){c=h?n:c;var w=oi(a,R,n,n,n,n,n,c);return w.placeholder=y_.placeholder,w}function w_(a,c,h){var w,$,T,O,I,B,ne=0,re=!1,le=!1,ge=!0;if(typeof a!="function")throw new kr(s);c=Or(c)||0,It(h)&&(re=!!h.leading,le="maxWait"in h,T=le?tn(Or(h.maxWait)||0,c):T,ge="trailing"in h?!!h.trailing:ge);function ke(Yt){var no=w,ci=$;return w=$=n,ne=Yt,O=a.apply(ci,no),O}function Ie(Yt){return ne=Yt,I=qc(nt,c),re?ke(Yt):O}function Qe(Yt){var no=Yt-B,ci=Yt-ne,F_=c-no;return le?En(F_,T-ci):F_}function Le(Yt){var no=Yt-B,ci=Yt-ne;return B===n||no>=c||no<0||le&&ci>=T}function nt(){var Yt=jf();if(Le(Yt))return at(Yt);I=qc(nt,Qe(Yt))}function at(Yt){return I=n,ge&&w?ke(Yt):(w=$=n,O)}function lr(){I!==n&&TS(I),ne=0,w=B=$=I=n}function Dn(){return I===n?O:at(jf())}function cr(){var Yt=jf(),no=Le(Yt);if(w=arguments,$=this,B=Yt,no){if(I===n)return Ie(B);if(le)return TS(I),I=qc(nt,c),ke(B)}return I===n&&(I=qc(nt,c)),O}return cr.cancel=lr,cr.flush=Dn,cr}var Y7=et(function(a,c){return lS(a,1,c)}),X7=et(function(a,c,h){return lS(a,Or(c)||0,h)});function Z7(a){return oi(a,U)}function zf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new kr(s);var h=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=h.cache;if(T.has($))return T.get($);var O=a.apply(this,w);return h.cache=T.set($,O)||T,O};return h.cache=new(zf.Cache||ni),h}zf.Cache=ni;function Bf(a){if(typeof a!="function")throw new kr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function q7(a){return m_(2,a)}var Q7=F6(function(a,c){c=c.length==1&&Ge(c[0])?Ot(c[0],ir(De())):Ot(hn(c,1),ir(De()));var h=c.length;return et(function(w){for(var $=-1,T=En(w.length,h);++$=c}),Js=hS(function(){return arguments}())?hS:function(a){return Bt(a)&&yt.call(a,"callee")&&!Jb.call(a,"callee")},Ge=ee.isArray,h4=Nb?ir(Nb):b6;function Hn(a){return a!=null&&Uf(a.length)&&!ai(a)}function Gt(a){return Bt(a)&&Hn(a)}function p4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Hi=kO||Iv,m4=Db?ir(Db):S6;function g4(a){return Bt(a)&&a.nodeType===1&&!Qc(a)}function v4(a){if(a==null)return!0;if(Hn(a)&&(Ge(a)||typeof a=="string"||typeof a.splice=="function"||Hi(a)||el(a)||Js(a)))return!a.length;var c=Cn(a);if(c==ct||c==J)return!a.size;if(Zc(a))return!ev(a).length;for(var h in a)if(yt.call(a,h))return!1;return!0}function y4(a,c){return Gc(a,c)}function w4(a,c,h){h=typeof h=="function"?h:n;var w=h?h(a,c):n;return w===n?Gc(a,c,n,h):!!w}function $v(a){if(!Bt(a))return!1;var c=On(a);return c==Me||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Qc(a)}function x4(a){return typeof a=="number"&&tS(a)}function ai(a){if(!It(a))return!1;var c=On(a);return c==je||c==Mt||c==he||c==L}function b_(a){return typeof a=="number"&&a==qe(a)}function Uf(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var S_=Ib?ir(Ib):E6;function b4(a,c){return a===c||Jg(a,c,gv(c))}function S4(a,c,h){return h=typeof h=="function"?h:n,Jg(a,c,gv(c),h)}function _4(a){return __(a)&&a!=+a}function E4(a){if(aN(a))throw new Ke(i);return pS(a)}function C4(a){return a===null}function $4(a){return a==null}function __(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Qc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=mf(a);if(c===null)return!0;var h=yt.call(c,"constructor")&&c.constructor;return typeof h=="function"&&h instanceof h&&df.call(h)==SO}var Rv=Lb?ir(Lb):C6;function R4(a){return b_(a)&&a>=-K&&a<=K}var E_=Fb?ir(Fb):$6;function Vf(a){return typeof a=="string"||!Ge(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==me}var el=jb?ir(jb):R6;function k4(a){return a===n}function T4(a){return Bt(a)&&Cn(a)==Re}function P4(a){return Bt(a)&&On(a)==ft}var A4=Of(tv),M4=Of(function(a,c){return a<=c});function C_(a){if(!a)return[];if(Hn(a))return Vf(a)?Jr(a):Wn(a);if(jc&&a[jc])return uO(a[jc]());var c=Cn(a),h=c==ct?Ug:c==J?lf:tl;return h(a)}function li(a){if(!a)return a===0?a:0;if(a=Or(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Z}return a===a?a:0}function qe(a){var c=li(a),h=c%1;return c===c?h?c-h:c:0}function $_(a){return a?Xs(qe(a),0,se):0}function Or(a){if(typeof a=="number")return a;if(ar(a))return H;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Hb(a);var h=hM.test(a);return h||mM.test(a)?GM(a.slice(2),h?2:8):fM.test(a)?H:+a}function R_(a){return Ro(a,Kn(a))}function O4(a){return a?Xs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var N4=qa(function(a,c){if(Zc(c)||Hn(c)){Ro(c,ln(c),a);return}for(var h in c)yt.call(c,h)&&Wc(a,h,c[h])}),k_=qa(function(a,c){Ro(c,Kn(c),a)}),Wf=qa(function(a,c,h,w){Ro(c,Kn(c),a,w)}),D4=qa(function(a,c,h,w){Ro(c,ln(c),a,w)}),I4=ii(Yg);function L4(a,c){var h=Za(a);return c==null?h:sS(h,c)}var F4=et(function(a,c){a=St(a);var h=-1,w=c.length,$=w>2?c[2]:n;for($&&Nn(c[0],c[1],$)&&(w=1);++h1),T}),Ro(a,pv(a),h),w&&(h=Pr(h,p|g|y,X6));for(var $=c.length;$--;)sv(h,c[$]);return h});function n8(a,c){return P_(a,Bf(De(c)))}var r8=ii(function(a,c){return a==null?{}:P6(a,c)});function P_(a,c){if(a==null)return{};var h=Ot(pv(a),function(w){return[w]});return c=De(c),bS(a,h,function(w,$){return c(w,$[0])})}function o8(a,c,h){c=Vi(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[ko(c[w])];T===n&&(w=$,T=h),a=ai(T)?T.call(a):T}return a}function i8(a,c,h){return a==null?a:Yc(a,c,h)}function s8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:Yc(a,c,h,w)}var A_=VS(ln),M_=VS(Kn);function a8(a,c,h){var w=Ge(a),$=w||Hi(a)||el(a);if(c=De(c,4),h==null){var T=a&&a.constructor;$?h=w?new T:[]:It(a)?h=ai(T)?Za(mf(a)):{}:h={}}return($?Rr:$o)(a,function(O,I,B){return c(h,O,I,B)}),h}function l8(a,c){return a==null?!0:sv(a,c)}function c8(a,c,h){return a==null?a:$S(a,c,cv(h))}function u8(a,c,h,w){return w=typeof w=="function"?w:n,a==null?a:$S(a,c,cv(h),w)}function tl(a){return a==null?[]:Bg(a,ln(a))}function d8(a){return a==null?[]:Bg(a,Kn(a))}function f8(a,c,h){return h===n&&(h=c,c=n),h!==n&&(h=Or(h),h=h===h?h:0),c!==n&&(c=Or(c),c=c===c?c:0),Xs(Or(a),c,h)}function h8(a,c,h){return c=li(c),h===n?(h=c,c=0):h=li(h),a=Or(a),w6(a,c,h)}function p8(a,c,h){if(h&&typeof h!="boolean"&&Nn(a,c,h)&&(c=h=n),h===n&&(typeof c=="boolean"?(h=c,c=n):typeof a=="boolean"&&(h=a,a=n)),a===n&&c===n?(a=0,c=1):(a=li(a),c===n?(c=a,a=0):c=li(c)),a>c){var w=a;a=c,c=w}if(h||a%1||c%1){var $=nS();return En(a+$*(c-a+KM("1e-"+(($+"").length-1))),c)}return rv(a,c)}var m8=Qa(function(a,c,h){return c=c.toLowerCase(),a+(h?O_(c):c)});function O_(a){return Pv(vt(a).toLowerCase())}function N_(a){return a=vt(a),a&&a.replace(vM,iO).replace(IM,"")}function g8(a,c,h){a=vt(a),c=sr(c);var w=a.length;h=h===n?w:Xs(qe(h),0,w);var $=h;return h-=c.length,h>=0&&a.slice(h,$)==c}function v8(a){return a=vt(a),a&&_g.test(a)?a.replace(Nc,sO):a}function y8(a){return a=vt(a),a&&Ye.test(a)?a.replace(G,"\\$&"):a}var w8=Qa(function(a,c,h){return a+(h?"-":"")+c.toLowerCase()}),x8=Qa(function(a,c,h){return a+(h?" ":"")+c.toLowerCase()}),b8=LS("toLowerCase");function S8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Mf(wf($),h)+a+Mf(yf($),h)}function _8(a,c,h){a=vt(a),c=qe(c);var w=c?Ha(a):0;return c&&w>>0,h?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Rv(c))&&(c=sr(c),!c&&Wa(a))?Wi(Jr(a),0,h):a.split(c,h)):[]}var P8=Qa(function(a,c,h){return a+(h?" ":"")+Pv(c)});function A8(a,c,h){return a=vt(a),h=h==null?0:Xs(qe(h),0,a.length),c=sr(c),a.slice(h,h+c.length)==c}function M8(a,c,h){var w=k.templateSettings;h&&Nn(a,c,h)&&(c=n),a=vt(a),c=Wf({},c,w,WS);var $=Wf({},c.imports,w.imports,WS),T=ln($),O=Bg($,T),I,B,ne=0,re=c.interpolate||nf,le="__p += '",ge=Vg((c.escape||nf).source+"|"+re.source+"|"+(re===Lc?dM:nf).source+"|"+(c.evaluate||nf).source+"|$","g"),ke="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++BM+"]")+` +`;a.replace(ge,function(Le,nt,at,lr,Dn,cr){return at||(at=lr),le+=a.slice(ne,cr).replace(yM,aO),nt&&(I=!0,le+=`' + +__e(`+nt+`) + +'`),Dn&&(B=!0,le+=`'; +`+Dn+`; +__p += '`),at&&(le+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),le+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)le=`with (obj) { +`+le+` +} +`;else if(cM.test(Ie))throw new Ke(l);le=(B?le.replace(bg,""):le).replace(Sg,"$1").replace(Jd,"$1;"),le="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(I?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+le+`return __p +}`;var Qe=I_(function(){return pt(T,ke+"return "+le).apply(n,O)});if(Qe.source=le,$v(Qe))throw Qe;return Qe}function O8(a){return vt(a).toLowerCase()}function N8(a){return vt(a).toUpperCase()}function D8(a,c,h){if(a=vt(a),a&&(h||c===n))return Hb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Kb(w,$),O=Gb(w,$)+1;return Wi(w,T,O).join("")}function I8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.slice(0,Xb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Gb(w,Jr(c))+1;return Wi(w,0,$).join("")}function L8(a,c,h){if(a=vt(a),a&&(h||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Kb(w,Jr(c));return Wi(w,$).join("")}function F8(a,c){var h=W,w=q;if(It(c)){var $="separator"in c?c.separator:$;h="length"in c?qe(c.length):h,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Wa(a)){var O=Jr(a);T=O.length}if(h>=T)return a;var I=h-Ha(w);if(I<1)return w;var B=O?Wi(O,0,I).join(""):a.slice(0,I);if($===n)return B+w;if(O&&(I+=B.length-I),Rv($)){if(a.slice(I).search($)){var ne,re=B;for($.global||($=Vg($.source,vt(hb.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var le=ne.index;B=B.slice(0,le===n?I:le)}}else if(a.indexOf(sr($),I)!=I){var ge=B.lastIndexOf($);ge>-1&&(B=B.slice(0,ge))}return B+w}function j8(a){return a=vt(a),a&&Dc.test(a)?a.replace(Oc,pO):a}var z8=Qa(function(a,c,h){return a+(h?" ":"")+c.toUpperCase()}),Pv=LS("toUpperCase");function D_(a,c,h){return a=vt(a),c=h?n:c,c===n?cO(a)?vO(a):eO(a):a.match(c)||[]}var I_=et(function(a,c){try{return or(a,n,c)}catch(h){return $v(h)?h:new Ke(h)}}),B8=ii(function(a,c){return Rr(c,function(h){h=ko(h),ri(a,h,Ev(a[h],a))}),a});function U8(a){var c=a==null?0:a.length,h=De();return a=c?Ot(a,function(w){if(typeof w[1]!="function")throw new kr(s);return[h(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var h=se,w=En(a,se);c=De(c),a-=se;for(var $=zg(w,c);++h0||c<0)?new ot(h):(a<0?h=h.takeRight(-a):a&&(h=h.drop(a)),c!==n&&(c=qe(c),h=c<0?h.dropRight(-c):h.take(c-a)),h)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(se)},$o(ot.prototype,function(a,c){var h=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=k[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(k.prototype[c]=function(){var O=this.__wrapped__,I=w?[1]:arguments,B=O instanceof ot,ne=I[0],re=B||Ge(O),le=function(nt){var at=$.apply(k,Fi([nt],I));return w&&ge?at[0]:at};re&&h&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var ge=this.__chain__,ke=!!this.__actions__.length,Ie=T&&!ge,Qe=B&&!ke;if(!T&&re){O=Qe?O:new ot(this);var Le=a.apply(O,I);return Le.__actions__.push({func:Lf,args:[le],thisArg:n}),new Tr(Le,ge)}return Ie&&Qe?a.apply(this,I):(Le=this.thru(le),Ie?w?Le.value()[0]:Le.value():Le)})}),Rr(["pop","push","shift","sort","splice","unshift"],function(a){var c=cf[a],h=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);k.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ge(T)?T:[],$)}return this[h](function(O){return c.apply(Ge(O)?O:[],$)})}}),$o(ot.prototype,function(a,c){var h=k[c];if(h){var w=h.name+"";yt.call(Xa,w)||(Xa[w]=[]),Xa[w].push({name:c,func:h})}}),Xa[Pf(n,_).name]=[{name:"wrapper",func:n}],ot.prototype.clone=jO,ot.prototype.reverse=zO,ot.prototype.value=BO,k.prototype.at=g7,k.prototype.chain=v7,k.prototype.commit=y7,k.prototype.next=w7,k.prototype.plant=b7,k.prototype.reverse=S7,k.prototype.toJSON=k.prototype.valueOf=k.prototype.value=_7,k.prototype.first=k.prototype.head,jc&&(k.prototype[jc]=x7),k},Ka=yO();Hs?((Hs.exports=Ka)._=Ka,Mg._=Ka):fn._=Ka}).call(Jc)})(zp,zp.exports);var wH=zp.exports;const xH=dm(wH);function Vr({width:e,height:t}){return e/t}function Bp(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function bH(e){return(t,n)=>e(n)-e(t)}class SH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const f=e(l);o.add(l),f.forEach((m,p)=>{const g=u+m,y=r.get(p),b=i.get(p);(b===void 0||b>g&&(b/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Bp(n/t/r)+2}function DP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function RH(e,t,n,r,o,i,s){const l=e.slice(t,n),u=DP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:f,padding:m}=t,p=new Map;p.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let b=i+g;by);b+=1){const S=RH(e,i,b,u,n,f,m);if(S===void 0)break;p.set(b,S)}return p}}function TH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=$H({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),f=CH(u,0,e.length);if(f===void 0)return;const m=[];for(let p=1;p({photo:b,index:S})).slice(f[p-1],f[p]),y=DP(g.map(({photo:b})=>b),o,n,r);m.push(g.map(({photo:b,index:S},E)=>({photo:b,layout:{height:y,width:y*Vr(b),index:S,photoIndex:E,photosCount:g.length}})))}return m}function eg(...e){return[...e].filter(t=>!!t).join(" ")}function IP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Bp((i-s)/t,5)})`}function PH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:IP("100%",e,t)}function a2(e,t,n){var r,o;return IP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function AH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${a2(l,t,n)}`).concat(a2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Nx(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:f}=e,{onClick:m}=i,p={display:"block",boxSizing:"content-box",width:PH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{m({event:E,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:p,className:eg("react-photo-album--photo",l),loading:"lazy",decoding:"async",...AH(r,o,i),...u},b=E=>{const{src:_,alt:x,srcSet:C,sizes:R,style:P,...M}=y;return d.createElement("img",{alt:x,...C?{srcSet:C,sizes:R}:null,src:_,style:E!=null&&E.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},S=(({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M})=>({display:E,boxSizing:_,width:x,aspectRatio:C,padding:R,marginBottom:P,cursor:M}))(p);return d.createElement(d.Fragment,null,(n=f==null?void 0:f({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:b,wrapperStyle:S}))!=null?n:b())}function MH({rowContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,f={className:eg("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nd.createElement(OH,{key:`row-${f}`,layoutOptions:n,rowIndex:f,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function DH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const f=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:m,weight:p})=>{let g=o.get(m);g||(g=[],o.set(m,g));const y=f+p,b=g[s+1];(!b||b.weight>y&&(b.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function LH(e,t,n,r){return IH(DH(e,t,n,r),t,r)}function FH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let f=i+1;fl||f===e.length));f+=1)u+=r/Vr(e[f])+t+2*n;return s}}function l2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((f,m)=>f+m,0);for(let f=0;f({photo:y,index:b})).slice(e[f],e[f+1]),p=o.reduce((y,b,S)=>y+(r[f]-r[S])*b,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-p)*o[f]/u;l.push(m.map(({photo:y,index:b},S)=>({photo:y,layout:{width:g,height:g/Vr(y),index:b,photoIndex:S,photosCount:m.length}})))}return l}function jH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((S,E)=>S+Vr(E),0)/e.length:1;for(let S=0;SMath.min(E,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:b}}const f=(e.reduce((y,b)=>y+n/Vr(b),0)+o*(e.length-r)+2*i*e.length)/r,m=FH({photos:e,targetColumnWidth:n,targetColumnHeight:f,spacing:o,padding:i}),p=LH(m,r,0,e.length);for(let y=0;yS+1/Vr(E),0)}const g=l2({path:p,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:f,columnsModel:m}=jH({photos:t,layoutOptions:n,targetColumnWidth:l});return m.findIndex(p=>p.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?LP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:m,columnsGaps:u,columnsRatios:f}}function zH({photos:e,layoutOptions:t}){return LP({photos:e,layoutOptions:t})}function BH({columnContainerProps:e,children:t}){return d.createElement("div",{...e},t)}function UH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const f=i.reduce((p,g)=>p+g,0),m=i.reduce((p,g,y)=>p+(o[n]-o[y])*g,0);return`calc((100% - ${Bp((r-1)*l+2*r*u+m,3)}px) * ${Bp(i[n]/f,5)} + ${2*u}px)`}function FP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:eg("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:UH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return d.createElement(d.Fragment,null,(n??BH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=zH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:f,columnsGaps:m}=l;return d.createElement(d.Fragment,null,u.map((p,g)=>d.createElement(FP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:m,columnsRatios:f,renderColumnContainer:o,columnContainerProps:s},p.map(({photo:y,layout:b})=>d.createElement(Nx,{key:y.key||y.src,photo:y,layout:b,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function jP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?jP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let m=0;m{const y=u.reduce((b,S,E)=>S[])).map(m=>m.map(({photo:p,index:g},y)=>({photo:p,layout:{width:l,height:l/Vr(p),index:g,photoIndex:y,photosCount:m.length}})))}function WH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jP({photos:t,layoutOptions:n});return l?d.createElement(d.Fragment,null,l.map((u,f)=>d.createElement(FP,{key:`masonry-column-${f}`,layoutOptions:n,columnsCount:l.length,columnIndex:f,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:m,layout:p})=>d.createElement(Nx,{key:m.key||m.src,photo:m,layout:p,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function HH({containerProps:e,children:t,containerRef:n}){return d.createElement("div",{ref:n,...e},t)}function KH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:eg("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return d.createElement(d.Fragment,null,(n??HH)({containerProps:u,containerRef:o,layout:t,children:r}))}function GH(e){const t=d.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function ZH(e,t){const[{containerWidth:n},r]=d.useReducer(YH,{containerWidth:t}),o=d.useRef(null),i=d.useRef();return{containerRef:d.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const f=()=>r({newContainerWidth:XH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});f(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(f),i.current.observe(l))},[e]),containerWidth:n}}const qH=Object.freeze([1200,600,300,0]);function Dx(e,t){return typeof e=="function"?e(t):e}function zP(e,t){return typeof e<"u"?Dx(e,t):void 0}function QH(e,t){const n=qH.findIndex(r=>r<=t);return Dx(e[n>=0?n:0],t)}function wh(e,t,n,r=0){const o=zP(e,t);return Math.round(Math.max(o===void 0?QH(n,t):o,r))}function JH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:wh(i,n,[5,4,3,2],1),spacing:wh(s,n,[20,15,10,5]),padding:wh(l,n,[0,0,0,0,0]),targetRowHeight:wh(r,n,[f=>f/5,f=>f/4,f=>f/3,f=>f/2]),rowConstraints:zP(o,n),sizes:u}}function eK(e,t,n){const{photos:r,componentsProps:o}=e,i=Dx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:f}=n;if(s==="rows"){const{singleRowMaxHeight:m}=f||{};if(m){const p=Math.floor(r.reduce((g,{width:y,height:b})=>g+y/b*m-2*u,u*r.length*2+l*(r.length-1)));p>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:p,...i.containerProps.style})}}}return i}function tK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?d.createElement(NH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?d.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u}):d.createElement(WH,{layoutOptions:n,renderColumnContainer:l,...u})}function nK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=ZH(GH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?JH({containerWidth:l,...e}):void 0,f=eK(e,l,u);return d.createElement(KH,{layout:n,containerRef:s,renderContainer:r,containerProps:f.containerProps},u&&tK(e,f,u))}function rK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const oK=d.forwardRef(rK),iK=oK;function sK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const aK=d.forwardRef(sK),lK=aK;function cK({title:e,titleId:t,...n},r){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?d.createElement("title",{id:t},e):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const uK=d.forwardRef(cK),dK=uK;function ki(e){return Array.isArray?Array.isArray(e):VP(e)==="[object Array]"}const fK=1/0;function hK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-fK?"-0":t}function pK(e){return e==null?"":hK(e)}function Bo(e){return typeof e=="string"}function BP(e){return typeof e=="number"}function mK(e){return e===!0||e===!1||gK(e)&&VP(e)=="[object Boolean]"}function UP(e){return typeof e=="object"}function gK(e){return UP(e)&&e!==null}function pr(e){return e!=null}function A0(e){return!e.trim().length}function VP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const vK="Incorrect 'index' type",yK=e=>`Invalid value for key ${e}`,wK=e=>`Pattern length exceeds max of ${e}.`,xK=e=>`Missing ${e} property in key`,bK=e=>`Property 'weight' in key '${e}' must be a positive integer`,c2=Object.prototype.hasOwnProperty;class SK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=WP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function WP(e){let t=null,n=null,r=null,o=1,i=null;if(Bo(e)||ki(e))r=e,t=u2(e),n=g1(e);else{if(!c2.call(e,"name"))throw new Error(xK("name"));const s=e.name;if(r=s,c2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(bK(s));t=u2(s),n=g1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function u2(e){return ki(e)?e:e.split(".")}function g1(e){return ki(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(pr(i))if(!s[l])n.push(i);else{let u=s[l];const f=i[u];if(!pr(f))return;if(l===s.length-1&&(Bo(f)||BP(f)||mK(f)))n.push(pK(f));else if(ki(f)){r=!0;for(let m=0,p=f.length;me.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Bo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Bo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(pr(s)){if(ki(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:f,value:m}=u.pop();if(pr(m))if(Bo(m)&&!A0(m)){let p={v:m,i:f,n:this.norm.get(m)};l.push(p)}else ki(m)&&m.forEach((p,g)=>{u.push({nestedArrIndex:g,value:p})})}r.$[i]=l}else if(Bo(s)&&!A0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function HP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Ix({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(WP)),o.setSources(t),o.create(),o}function PK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Ix({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function xh(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function AK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const la=32;function MK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:f=He.ignoreLocation}={}){if(t.length>la)throw new Error(wK(la));const m=t.length,p=e.length,g=Math.max(0,Math.min(r,p));let y=i,b=g;const S=l>1||u,E=S?Array(p):[];let _;for(;(_=e.indexOf(t,b))>-1;){let A=xh(t,{currentLocation:_,expectedLocation:g,distance:o,ignoreLocation:f});if(y=Math.min(A,y),b=_+m,S){let D=0;for(;D=W;V-=1){let F=V-1,N=n[e.charAt(F)];if(S&&(E[F]=+!!N),X[V]=(X[V+1]<<1|1)&N,A&&(X[V]|=(x[V+1]|x[V])<<1|1|x[V+1]),X[V]&P&&(C=xh(t,{errors:A,currentLocation:F,expectedLocation:g,distance:o,ignoreLocation:f}),C<=y)){if(y=C,b=F,b<=g)break;W=Math.max(1,2*g-b)}}if(xh(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:f})>y)break;x=X}const M={isMatch:b>=0,score:Math.max(.001,C)};if(S){const A=AK(E,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},p=this.pattern.length;if(p>la){let g=0;const y=p%la,b=p-y;for(;g{const{isMatch:_,score:x,indices:C}=MK(t,b,S,{location:o+E,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:f});_&&(g=!0),p+=x,_&&C&&(m=[...m,...C])});let y={isMatch:g,score:g?p/this.chunks.length:1};return g&&r&&(y.indices=m),y}}class js{constructor(t){this.pattern=t}static isMultiMatch(t){return d2(t,this.multiRegex)}static isSingleMatch(t){return d2(t,this.singleRegex)}search(){}}function d2(e,t){const n=e.match(t);return n?n[1]:null}class NK extends js{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class DK extends js{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class IK extends js{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class LK extends js{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class FK extends js{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class jK extends js{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class GP extends js{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:f=He.ignoreLocation}={}){super(t),this._bitapSearch=new KP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:f})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class YP extends js{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const v1=[NK,YP,IK,LK,jK,FK,DK,GP],f2=v1.length,zK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,BK="|";function UK(e,t={}){return e.split(BK).map(n=>{let r=n.trim().split(zK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[Up.AND]||e[Up.OR]),KK=e=>!!e[x1.PATH],GK=e=>!ki(e)&&UP(e)&&!b1(e),h2=e=>({[Up.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function XP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=KK(o);if(!s&&i.length>1&&!b1(o))return r(h2(o));if(GK(o)){const u=s?o[x1.PATH]:i[0],f=s?o[x1.PATTERN]:o[u];if(!Bo(f))throw new Error(yK(u));const m={keyId:g1(u),pattern:f};return n&&(m.searcher=w1(f,t)),m}let l={children:[],operator:i[0]};return i.forEach(u=>{const f=o[u];ki(f)&&f.forEach(m=>{l.children.push(r(m))})}),l};return b1(e)||(e=h2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function XK(e,t){const n=e.matches;t.matches=[],pr(n)&&n.forEach(r=>{if(!pr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function ZK(e,t){t.score=e.score}function qK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(XK),r&&o.push(ZK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class kc{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new SK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Ix))throw new Error(vK);this._myIndex=n||HP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){pr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),qK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=w1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:f,value:i,norm:l,indices:m}]})}),o}_searchLogical(t){const n=XP(t,this.options),r=(l,u,f)=>{if(!l.children){const{keyId:p,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(p),value:this._myIndex.getValueForItemAtKeyId(u,p),searcher:g});return y&&y.length?[{idx:f,item:u,matches:y}]:[]}const m=[];for(let p=0,g=l.children.length;p{if(pr(l)){let f=r(n,l,u);f.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),f.forEach(({matches:m})=>{i[u].matches.push(...m)}))}}),s}_searchObjectList(t){const n=w1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!pr(s))return;let u=[];r.forEach((f,m)=>{u.push(...this._findMatches({key:f,value:s[m],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!pr(n))return[];let o=[];if(ki(n))n.forEach(({v:i,i:s,n:l})=>{if(!pr(i))return;const{isMatch:u,score:f,indices:m}=r.searchIn(i);u&&o.push({score:f,key:t,value:i,idx:s,norm:l,indices:m})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:f}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:f})}return o}}kc.version="7.0.0";kc.createIndex=HP;kc.parseIndex=PK;kc.config=He;kc.parseQuery=XP;HK(WK);function Gd(e){const t=e+"CollectionProvider",[n,r]=Mn(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:b,children:S}=y,E=Fe.useRef(null),_=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:b,itemMap:_,collectionRef:E},S)},l=e+"CollectionSlot",u=Fe.forwardRef((y,b)=>{const{scope:S,children:E}=y,_=i(l,S),x=Be(b,_.collectionRef);return Fe.createElement(Zo,{ref:x},E)}),f=e+"CollectionItemSlot",m="data-radix-collection-item",p=Fe.forwardRef((y,b)=>{const{scope:S,children:E,..._}=y,x=Fe.useRef(null),C=Be(b,x),R=i(f,S);return Fe.useEffect(()=>(R.itemMap.set(x,{ref:x,..._}),()=>void R.itemMap.delete(x))),Fe.createElement(Zo,{[m]:"",ref:C},E)});function g(y){const b=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const E=b.collectionRef.current;if(!E)return[];const _=Array.from(E.querySelectorAll(`[${m}]`));return Array.from(b.itemMap.values()).sort((R,P)=>_.indexOf(R.ref.current)-_.indexOf(P.ref.current))},[b.collectionRef,b.itemMap])}return[{Provider:s,Slot:u,ItemSlot:p},g,r]}const QK=d.createContext(void 0);function Tc(e){const t=d.useContext(QK);return e||t||"ltr"}const M0="rovingFocusGroup.onEntryFocus",JK={bubbles:!1,cancelable:!0},Lx="RovingFocusGroup",[S1,ZP,eG]=Gd(Lx),[tG,tg]=Mn(Lx,[eG]),[nG,rG]=tG(Lx),oG=d.forwardRef((e,t)=>d.createElement(S1.Provider,{scope:e.__scopeRovingFocusGroup},d.createElement(S1.Slot,{scope:e.__scopeRovingFocusGroup},d.createElement(iG,Y({},e,{ref:t}))))),iG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:f,...m}=e,p=d.useRef(null),g=Be(t,p),y=Tc(i),[b=null,S]=Zr({prop:s,defaultProp:l,onChange:u}),[E,_]=d.useState(!1),x=Ft(f),C=ZP(n),R=d.useRef(!1),[P,M]=d.useState(0);return d.useEffect(()=>{const A=p.current;if(A)return A.addEventListener(M0,x),()=>A.removeEventListener(M0,x)},[x]),d.createElement(nG,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:b,onItemFocus:d.useCallback(A=>S(A),[S]),onItemShiftTab:d.useCallback(()=>_(!0),[]),onFocusableItemAdd:d.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:d.useCallback(()=>M(A=>A-1),[])},d.createElement(Pe.div,Y({tabIndex:E||P===0?-1:0,"data-orientation":r},m,{ref:g,style:{outline:"none",...e.style},onMouseDown:de(e.onMouseDown,()=>{R.current=!0}),onFocus:de(e.onFocus,A=>{const D=!R.current;if(A.target===A.currentTarget&&D&&!E){const U=new CustomEvent(M0,JK);if(A.currentTarget.dispatchEvent(U),!U.defaultPrevented){const W=C().filter(F=>F.focusable),q=W.find(F=>F.active),X=W.find(F=>F.id===b),V=[q,X,...W].filter(Boolean).map(F=>F.ref.current);qP(V)}}R.current=!1}),onBlur:de(e.onBlur,()=>_(!1))})))}),sG="RovingFocusGroupItem",aG=d.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,f=rG(sG,n),m=f.currentTabStopId===u,p=ZP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=f;return d.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),d.createElement(S1.ItemSlot,{scope:n,id:u,focusable:r,active:o},d.createElement(Pe.span,Y({tabIndex:m?0:-1,"data-orientation":f.orientation},s,{ref:t,onMouseDown:de(e.onMouseDown,b=>{r?f.onItemFocus(u):b.preventDefault()}),onFocus:de(e.onFocus,()=>f.onItemFocus(u)),onKeyDown:de(e.onKeyDown,b=>{if(b.key==="Tab"&&b.shiftKey){f.onItemShiftTab();return}if(b.target!==b.currentTarget)return;const S=uG(b,f.orientation,f.dir);if(S!==void 0){b.preventDefault();let _=p().filter(x=>x.focusable).map(x=>x.ref.current);if(S==="last")_.reverse();else if(S==="prev"||S==="next"){S==="prev"&&_.reverse();const x=_.indexOf(b.currentTarget);_=f.loop?dG(_,x+1):_.slice(x+1)}setTimeout(()=>qP(_))}})})))}),lG={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cG(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function uG(e,t,n){const r=cG(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lG[r]}function qP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function dG(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const QP=oG,JP=aG,e5="Tabs",[fG,xte]=Mn(e5,[tg]),t5=tg(),[hG,Fx]=fG(e5),pG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...f}=e,m=Tc(l),[p,g]=Zr({prop:r,onChange:o,defaultProp:i});return d.createElement(hG,{scope:n,baseId:nr(),value:p,onValueChange:g,orientation:s,dir:m,activationMode:u},d.createElement(Pe.div,Y({dir:m,"data-orientation":s},f,{ref:t})))}),mG="TabsList",gG=d.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Fx(mG,n),s=t5(n);return d.createElement(QP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),d.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),vG="TabsTrigger",yG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Fx(vG,n),l=t5(n),u=n5(s.baseId,r),f=r5(s.baseId,r),m=r===s.value;return d.createElement(JP,Y({asChild:!0},l,{focusable:!o,active:m}),d.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":m,"aria-controls":f,"data-state":m?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:de(e.onMouseDown,p=>{!o&&p.button===0&&p.ctrlKey===!1?s.onValueChange(r):p.preventDefault()}),onKeyDown:de(e.onKeyDown,p=>{[" ","Enter"].includes(p.key)&&s.onValueChange(r)}),onFocus:de(e.onFocus,()=>{const p=s.activationMode!=="manual";!m&&!o&&p&&s.onValueChange(r)})})))}),wG="TabsContent",xG=d.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Fx(wG,n),u=n5(l.baseId,r),f=r5(l.baseId,r),m=r===l.value,p=d.useRef(m);return d.useEffect(()=>{const g=requestAnimationFrame(()=>p.current=!1);return()=>cancelAnimationFrame(g)},[]),d.createElement(Sn,{present:o||m},({present:g})=>d.createElement(Pe.div,Y({"data-state":m?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:f,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:p.current?"0s":void 0}}),g&&i))});function n5(e,t){return`${e}-trigger-${t}`}function r5(e,t){return`${e}-content-${t}`}const bG=pG,o5=gG,i5=yG,s5=xG,a5=bG,jx=d.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));jx.displayName=o5.displayName;const pa=d.forwardRef(({className:e,...t},n)=>v.jsx(i5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));pa.displayName=i5.displayName;const Su=d.forwardRef(({className:e,...t},n)=>v.jsx(s5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));Su.displayName=s5.displayName;function fd(e,[t,n]){return Math.min(n,Math.max(t,e))}function zx(e){const t=d.useRef({value:e,previous:e});return d.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const SG=[" ","Enter","ArrowUp","ArrowDown"],_G=[" ","Enter"],ng="Select",[rg,og,EG]=Gd(ng),[Pc,bte]=Mn(ng,[EG,Fs]),Bx=Fs(),[CG,Fa]=Pc(ng),[$G,RG]=Pc(ng),kG=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:f,name:m,autoComplete:p,disabled:g,required:y}=e,b=Bx(t),[S,E]=d.useState(null),[_,x]=d.useState(null),[C,R]=d.useState(!1),P=Tc(f),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[D,U]=Zr({prop:s,defaultProp:l,onChange:u}),W=d.useRef(null),q=S?!!S.closest("form"):!0,[X,ae]=d.useState(new Set),V=Array.from(X).map(F=>F.props.value).join(";");return d.createElement(jd,b,d.createElement(CG,{required:y,scope:t,trigger:S,onTriggerChange:E,valueNode:_,onValueNodeChange:x,valueNodeHasChildren:C,onValueNodeHasChildrenChange:R,contentId:nr(),value:D,onValueChange:U,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:W,disabled:g},d.createElement(rg.Provider,{scope:t},d.createElement($G,{scope:e.__scopeSelect,onNativeOptionAdd:d.useCallback(F=>{ae(N=>new Set(N).add(F))},[]),onNativeOptionRemove:d.useCallback(F=>{ae(N=>{const ie=new Set(N);return ie.delete(F),ie})},[])},n)),q?d.createElement(f5,{key:V,"aria-hidden":!0,required:y,tabIndex:-1,name:m,autoComplete:p,value:D,onChange:F=>U(F.target.value),disabled:g},D===void 0?d.createElement("option",{value:""}):null,Array.from(X)):null))},TG="SelectTrigger",PG=d.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=Bx(n),s=Fa(TG,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),f=og(n),[m,p,g]=h5(b=>{const S=f().filter(x=>!x.disabled),E=S.find(x=>x.value===s.value),_=p5(S,b,E);_!==void 0&&s.onValueChange(_.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return d.createElement(Vm,Y({asChild:!0},i),d.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":d5(s.value)?"":void 0},o,{ref:u,onClick:de(o.onClick,b=>{b.currentTarget.focus()}),onPointerDown:de(o.onPointerDown,b=>{const S=b.target;S.hasPointerCapture(b.pointerId)&&S.releasePointerCapture(b.pointerId),b.button===0&&b.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(b.pageX),y:Math.round(b.pageY)},b.preventDefault())}),onKeyDown:de(o.onKeyDown,b=>{const S=m.current!=="";!(b.ctrlKey||b.altKey||b.metaKey)&&b.key.length===1&&p(b.key),!(S&&b.key===" ")&&SG.includes(b.key)&&(y(),b.preventDefault())})})))}),AG="SelectValue",MG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Fa(AG,n),{onValueNodeHasChildrenChange:f}=u,m=i!==void 0,p=Be(t,u.onValueNodeChange);return An(()=>{f(m)},[f,m]),d.createElement(Pe.span,Y({},l,{ref:p,style:{pointerEvents:"none"}}),d5(u.value)?d.createElement(d.Fragment,null,s):i)}),OG=d.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return d.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),NG=e=>d.createElement(zd,Y({asChild:!0},e)),dc="SelectContent",DG=d.forwardRef((e,t)=>{const n=Fa(dc,e.__scopeSelect),[r,o]=d.useState();if(An(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Is.createPortal(d.createElement(l5,{scope:e.__scopeSelect},d.createElement(rg.Slot,{scope:e.__scopeSelect},d.createElement("div",null,e.children))),i):null}return d.createElement(IG,Y({},e,{ref:t}))}),hi=10,[l5,ja]=Pc(dc),IG=d.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E,..._}=e,x=Fa(dc,n),[C,R]=d.useState(null),[P,M]=d.useState(null),A=Be(t,he=>R(he)),[D,U]=d.useState(null),[W,q]=d.useState(null),X=og(n),[ae,V]=d.useState(!1),F=d.useRef(!1);d.useEffect(()=>{if(C)return Qm(C)},[C]),Xm();const N=d.useCallback(he=>{const[xe,...$e]=X().map(je=>je.ref.current),[Ae]=$e.slice(-1),Me=document.activeElement;for(const je of he)if(je===Me||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Me))return},[X,P]),ie=d.useCallback(()=>N([D,C]),[N,D,C]);d.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Z}=x;d.useEffect(()=>{if(C){let he={x:0,y:0};const xe=Ae=>{var Me,je,Mt,ct;he={x:Math.abs(Math.round(Ae.pageX)-((Me=(je=Z.current)===null||je===void 0?void 0:je.x)!==null&&Me!==void 0?Me:0)),y:Math.abs(Math.round(Ae.pageY)-((Mt=(ct=Z.current)===null||ct===void 0?void 0:ct.y)!==null&&Mt!==void 0?Mt:0))}},$e=Ae=>{he.x<=10&&he.y<=10?Ae.preventDefault():C.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Z.current=null};return Z.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[C,K,Z]),d.useEffect(()=>{const he=()=>K(!1);return window.addEventListener("blur",he),window.addEventListener("resize",he),()=>{window.removeEventListener("blur",he),window.removeEventListener("resize",he)}},[K]);const[H,se]=h5(he=>{const xe=X().filter(Me=>!Me.disabled),$e=xe.find(Me=>Me.ref.current===document.activeElement),Ae=p5(xe,he,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ce=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&(U(he),Ae&&(F.current=!0))},[x.value]),Ve=d.useCallback(()=>C==null?void 0:C.focus(),[C]),Ue=d.useCallback((he,xe,$e)=>{const Ae=!F.current&&!$e;(x.value!==void 0&&x.value===xe||Ae)&&q(he)},[x.value]),We=r==="popper"?p2:LG,Oe=We===p2?{side:l,sideOffset:u,align:f,alignOffset:m,arrowPadding:p,collisionBoundary:g,collisionPadding:y,sticky:b,hideWhenDetached:S,avoidCollisions:E}:{};return d.createElement(l5,{scope:n,content:C,viewport:P,onViewportChange:M,itemRefCallback:ce,selectedItem:D,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:W,position:r,isPositioned:ae,searchRef:H},d.createElement(qm,{as:Zo,allowPinchZoom:!0},d.createElement(Ym,{asChild:!0,trapped:x.open,onMountAutoFocus:he=>{he.preventDefault()},onUnmountAutoFocus:de(o,he=>{var xe;(xe=x.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),he.preventDefault()})},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:he=>he.preventDefault(),onDismiss:()=>x.onOpenChange(!1)},d.createElement(We,Y({role:"listbox",id:x.contentId,"data-state":x.open?"open":"closed",dir:x.dir,onContextMenu:he=>he.preventDefault()},_,Oe,{onPlaced:()=>V(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:de(_.onKeyDown,he=>{const xe=he.ctrlKey||he.altKey||he.metaKey;if(he.key==="Tab"&&he.preventDefault(),!xe&&he.key.length===1&&se(he.key),["ArrowUp","ArrowDown","Home","End"].includes(he.key)){let Ae=X().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);if(["ArrowUp","End"].includes(he.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(he.key)){const Me=he.target,je=Ae.indexOf(Me);Ae=Ae.slice(je+1)}setTimeout(()=>N(Ae)),he.preventDefault()}})}))))))}),LG=d.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Fa(dc,n),s=ja(dc,n),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Be(t,A=>m(A)),g=og(n),y=d.useRef(!1),b=d.useRef(!0),{viewport:S,selectedItem:E,selectedItemText:_,focusSelectedItem:x}=s,C=d.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&f&&S&&E&&_){const A=i.trigger.getBoundingClientRect(),D=f.getBoundingClientRect(),U=i.valueNode.getBoundingClientRect(),W=_.getBoundingClientRect();if(i.dir!=="rtl"){const Me=W.left-D.left,je=U.left-Me,Mt=A.left-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Me=D.right-W.right,je=window.innerWidth-U.right-Me,Mt=window.innerWidth-A.right-je,ct=A.width+Mt,Kt=Math.max(ct,D.width),Er=window.innerWidth-hi,gt=fd(je,[hi,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const q=g(),X=window.innerHeight-hi*2,ae=S.scrollHeight,V=window.getComputedStyle(f),F=parseInt(V.borderTopWidth,10),N=parseInt(V.paddingTop,10),ie=parseInt(V.borderBottomWidth,10),K=parseInt(V.paddingBottom,10),Z=F+N+ae+K+ie,H=Math.min(E.offsetHeight*5,Z),se=window.getComputedStyle(S),ce=parseInt(se.paddingTop,10),Ve=parseInt(se.paddingBottom,10),Ue=A.top+A.height/2-hi,We=X-Ue,Oe=E.offsetHeight/2,he=E.offsetTop+Oe,xe=F+N+he,$e=Z-xe;if(xe<=Ue){const Me=E===q[q.length-1].ref.current;l.style.bottom="0px";const je=f.clientHeight-S.offsetTop-S.offsetHeight,Mt=Math.max(We,Oe+(Me?Ve:0)+je+ie),ct=xe+Mt;l.style.height=ct+"px"}else{const Me=E===q[0].ref.current;l.style.top="0px";const Mt=Math.max(Ue,F+S.offsetTop+(Me?ce:0)+Oe)+$e;l.style.height=Mt+"px",S.scrollTop=xe-Ue+S.offsetTop}l.style.margin=`${hi}px 0`,l.style.minHeight=H+"px",l.style.maxHeight=X+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,f,S,E,_,i.dir,r]);An(()=>C(),[C]);const[R,P]=d.useState();An(()=>{f&&P(window.getComputedStyle(f).zIndex)},[f]);const M=d.useCallback(A=>{A&&b.current===!0&&(C(),x==null||x(),b.current=!1)},[C,x]);return d.createElement(FG,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},d.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R}},d.createElement(Pe.div,Y({},o,{ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),p2=d.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=hi,...i}=e,s=Bx(n);return d.createElement(Wm,Y({},s,i,{ref:t,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)"}}))}),[FG,Ux]=Pc(dc,{}),m2="SelectViewport",jG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=ja(m2,n),i=Ux(m2,n),s=Be(t,o.onViewportChange),l=d.useRef(0);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(rg.Slot,{scope:n},d.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:de(r.onScroll,u=>{const f=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=i;if(p!=null&&p.current&&m){const g=Math.abs(l.current-f.scrollTop);if(g>0){const y=window.innerHeight-hi*2,b=parseFloat(m.style.minHeight),S=parseFloat(m.style.height),E=Math.max(b,S);if(E0?C:0,m.style.justifyContent="flex-end")}}}l.current=f.scrollTop})}))))}),zG="SelectGroup",[BG,UG]=Pc(zG),VG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return d.createElement(BG,{scope:n,id:o},d.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),WG="SelectLabel",HG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=UG(WG,n);return d.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),_1="SelectItem",[KG,c5]=Pc(_1),GG=d.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Fa(_1,n),u=ja(_1,n),f=l.value===r,[m,p]=d.useState(i??""),[g,y]=d.useState(!1),b=Be(t,_=>{var x;return(x=u.itemRefCallback)===null||x===void 0?void 0:x.call(u,_,r,o)}),S=nr(),E=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 d.createElement(KG,{scope:n,value:r,disabled:o,textId:S,isSelected:f,onItemTextChange:d.useCallback(_=>{p(x=>{var C;return x||((C=_==null?void 0:_.textContent)!==null&&C!==void 0?C:"").trim()})},[])},d.createElement(rg.ItemSlot,{scope:n,value:r,disabled:o,textValue:m},d.createElement(Pe.div,Y({role:"option","aria-labelledby":S,"data-highlighted":g?"":void 0,"aria-selected":f&&g,"data-state":f?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:b,onFocus:de(s.onFocus,()=>y(!0)),onBlur:de(s.onBlur,()=>y(!1)),onPointerUp:de(s.onPointerUp,E),onPointerMove:de(s.onPointerMove,_=>{if(o){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}else _.currentTarget.focus({preventScroll:!0})}),onPointerLeave:de(s.onPointerLeave,_=>{if(_.currentTarget===document.activeElement){var x;(x=u.onItemLeave)===null||x===void 0||x.call(u)}}),onKeyDown:de(s.onKeyDown,_=>{var x;((x=u.searchRef)===null||x===void 0?void 0:x.current)!==""&&_.key===" "||(_G.includes(_.key)&&E(),_.key===" "&&_.preventDefault())})}))))}),bh="SelectItemText",YG=d.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Fa(bh,n),l=ja(bh,n),u=c5(bh,n),f=RG(bh,n),[m,p]=d.useState(null),g=Be(t,_=>p(_),u.onItemTextChange,_=>{var x;return(x=l.itemTextRefCallback)===null||x===void 0?void 0:x.call(l,_,u.value,u.disabled)}),y=m==null?void 0:m.textContent,b=d.useMemo(()=>d.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:S,onNativeOptionRemove:E}=f;return An(()=>(S(b),()=>E(b)),[S,E,b]),d.createElement(d.Fragment,null,d.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Is.createPortal(i.children,s.valueNode):null)}),XG="SelectItemIndicator",ZG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return c5(XG,n).isSelected?d.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),g2="SelectScrollUpButton",qG=d.forwardRef((e,t)=>{const n=ja(g2,e.__scopeSelect),r=Ux(g2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollTop>0;i(m)};var l=f;const u=n.viewport;return f(),u.addEventListener("scroll",f),()=>u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),v2="SelectScrollDownButton",QG=d.forwardRef((e,t)=>{const n=ja(v2,e.__scopeSelect),r=Ux(v2,e.__scopeSelect),[o,i]=d.useState(!1),s=Be(t,r.onScrollButtonChange);return An(()=>{if(n.viewport&&n.isPositioned){let f=function(){const m=u.scrollHeight-u.clientHeight,p=Math.ceil(u.scrollTop)u.removeEventListener("scroll",f)}},[n.viewport,n.isPositioned]),o?d.createElement(u5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),u5=d.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=ja("SelectScrollButton",n),s=d.useRef(null),l=og(n),u=d.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return d.useEffect(()=>()=>u(),[u]),An(()=>{var f;const m=l().find(p=>p.ref.current===document.activeElement);m==null||(f=m.ref.current)===null||f===void 0||f.scrollIntoView({block:"nearest"})},[l]),d.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:de(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:de(o.onPointerMove,()=>{var f;(f=i.onItemLeave)===null||f===void 0||f.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:de(o.onPointerLeave,()=>{u()})}))}),JG=d.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return d.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function d5(e){return e===""||e===void 0}const f5=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=d.useRef(null),i=Be(t,o),s=zx(n);return d.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,m=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&m){const p=new Event("change",{bubbles:!0});m.call(l,n),l.dispatchEvent(p)}},[s,n]),d.createElement(Hm,{asChild:!0},d.createElement("select",Y({},r,{ref:i,defaultValue:n})))});f5.displayName="BubbleSelect";function h5(e){const t=Ft(e),n=d.useRef(""),r=d.useRef(0),o=d.useCallback(s=>{const l=n.current+s;t(l),function u(f){n.current=f,window.clearTimeout(r.current),f!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=d.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function p5(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=eY(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function eY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const tY=kG,m5=PG,nY=MG,rY=OG,oY=NG,g5=DG,iY=jG,sY=VG,v5=HG,y5=GG,aY=YG,lY=ZG,w5=qG,x5=QG,b5=JG,Uo=tY,vi=sY,Vo=nY,go=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(m5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(rY,{asChild:!0,children:v.jsx(Zj,{className:"h-4 w-4 opacity-50"})})]}));go.displayName=m5.displayName;const S5=d.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(rz,{})}));S5.displayName=w5.displayName;const _5=d.forwardRef(({className:e,...t},n)=>v.jsx(x5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Jj,{})}));_5.displayName=x5.displayName;const vo=d.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(oY,{children:v.jsxs(g5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(S5,{}),v.jsx(iY,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(_5,{})]})}));vo.displayName=g5.displayName;const cY=d.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));cY.displayName=v5.displayName;const yo=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(y5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(lY,{children:v.jsx(yT,{className:"h-4 w-4"})})}),v.jsx(aY,{children:t})]}));yo.displayName=y5.displayName;const uY=d.forwardRef(({className:e,...t},n)=>v.jsx(b5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));uY.displayName=b5.displayName;function dY(e,t){return d.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const E5="ScrollArea",[C5,Ste]=Mn(E5),[fY,qr]=C5(E5),hY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=d.useState(null),[f,m]=d.useState(null),[p,g]=d.useState(null),[y,b]=d.useState(null),[S,E]=d.useState(null),[_,x]=d.useState(0),[C,R]=d.useState(0),[P,M]=d.useState(!1),[A,D]=d.useState(!1),U=Be(t,q=>u(q)),W=Tc(o);return d.createElement(fY,{scope:n,type:r,dir:W,scrollHideDelay:i,scrollArea:l,viewport:f,onViewportChange:m,content:p,onContentChange:g,scrollbarX:y,onScrollbarXChange:b,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:S,onScrollbarYChange:E,scrollbarYEnabled:A,onScrollbarYEnabledChange:D,onCornerWidthChange:x,onCornerHeightChange:R},d.createElement(Pe.div,Y({dir:W},s,{ref:U,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...e.style}})))}),pY="ScrollAreaViewport",mY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pY,n),s=d.useRef(null),l=Be(t,s,i.onViewportChange);return d.createElement(d.Fragment,null,d.createElement("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}"}}),d.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),d.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),Oi="ScrollAreaScrollbar",$5=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return d.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?d.createElement(gY,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?d.createElement(vY,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?d.createElement(R5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?d.createElement(Vx,Y({},r,{ref:t})):null}),gY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),[i,s]=d.useState(!1);return d.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const f=()=>{window.clearTimeout(u),s(!0)},m=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",f),l.addEventListener("pointerleave",m),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",f),l.removeEventListener("pointerleave",m)}}},[o.scrollArea,o.scrollHideDelay]),d.createElement(Sn,{present:n||i},d.createElement(R5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),vY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr(Oi,e.__scopeScrollArea),i=e.orientation==="horizontal",s=sg(()=>u("SCROLL_END"),100),[l,u]=dY("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 d.useEffect(()=>{if(l==="idle"){const f=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(f)}},[l,o.scrollHideDelay,u]),d.useEffect(()=>{const f=o.viewport,m=i?"scrollLeft":"scrollTop";if(f){let p=f[m];const g=()=>{const y=f[m];p!==y&&(u("SCROLL"),s()),p=y};return f.addEventListener("scroll",g),()=>f.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),d.createElement(Sn,{present:n||l!=="hidden"},d.createElement(Vx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:de(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:de(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),R5=d.forwardRef((e,t)=>{const n=qr(Oi,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=d.useState(!1),l=e.orientation==="horizontal",u=sg(()=>{if(n.viewport){const f=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr(Oi,e.__scopeScrollArea),i=d.useRef(null),s=d.useRef(0),[l,u]=d.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),f=A5(l.viewport,l.content),m={...r,sizes:l,onSizesChange:u,hasThumb:f>0&&f<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function p(g,y){return CY(g,s.current,l,y)}return n==="horizontal"?d.createElement(yY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=y2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=p(g,o.dir))}})):n==="vertical"?d.createElement(wY,Y({},m,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=y2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=p(g))}})):null}),yY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarXChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"horizontal"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.x),onDragScroll:m=>e.onDragScroll(m.x),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollLeft+m.deltaX;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:Vp(s.paddingLeft),paddingEnd:Vp(s.paddingRight)}})}}))}),wY=d.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr(Oi,e.__scopeScrollArea),[s,l]=d.useState(),u=d.useRef(null),f=Be(t,u,i.onScrollbarYChange);return d.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),d.createElement(T5,Y({"data-orientation":"vertical"},o,{ref:f,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":ig(n)+"px",...e.style},onThumbPointerDown:m=>e.onThumbPointerDown(m.y),onDragScroll:m=>e.onDragScroll(m.y),onWheelScroll:(m,p)=>{if(i.viewport){const g=i.viewport.scrollTop+m.deltaY;e.onWheelScroll(g),O5(g,p)&&m.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:Vp(s.paddingTop),paddingEnd:Vp(s.paddingBottom)}})}}))}),[xY,k5]=C5(Oi),T5=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:f,onWheelScroll:m,onResize:p,...g}=e,y=qr(Oi,n),[b,S]=d.useState(null),E=Be(t,U=>S(U)),_=d.useRef(null),x=d.useRef(""),C=y.viewport,R=r.content-r.viewport,P=Ft(m),M=Ft(u),A=sg(p,10);function D(U){if(_.current){const W=U.clientX-_.current.left,q=U.clientY-_.current.top;f({x:W,y:q})}}return d.useEffect(()=>{const U=W=>{const q=W.target;(b==null?void 0:b.contains(q))&&P(W,R)};return document.addEventListener("wheel",U,{passive:!1}),()=>document.removeEventListener("wheel",U,{passive:!1})},[C,b,R,P]),d.useEffect(M,[r,M]),fc(b,A),fc(y.content,A),d.createElement(xY,{scope:n,scrollbar:b,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},d.createElement(Pe.div,Y({},g,{ref:E,style:{position:"absolute",...g.style},onPointerDown:de(e.onPointerDown,U=>{U.button===0&&(U.target.setPointerCapture(U.pointerId),_.current=b.getBoundingClientRect(),x.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),D(U))}),onPointerMove:de(e.onPointerMove,D),onPointerUp:de(e.onPointerUp,U=>{const W=U.target;W.hasPointerCapture(U.pointerId)&&W.releasePointerCapture(U.pointerId),document.body.style.webkitUserSelect=x.current,y.viewport&&(y.viewport.style.scrollBehavior=""),_.current=null})})))}),E1="ScrollAreaThumb",bY=d.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=k5(E1,e.__scopeScrollArea);return d.createElement(Sn,{present:n||o.hasThumb},d.createElement(SY,Y({ref:t},r)))}),SY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(E1,n),s=k5(E1,n),{onThumbPositionChange:l}=s,u=Be(t,p=>s.onThumbChange(p)),f=d.useRef(),m=sg(()=>{f.current&&(f.current(),f.current=void 0)},100);return d.useEffect(()=>{const p=i.viewport;if(p){const g=()=>{if(m(),!f.current){const y=$Y(p,l);f.current=y,l()}};return l(),p.addEventListener("scroll",g),()=>p.removeEventListener("scroll",g)}},[i.viewport,m,l]),d.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:de(e.onPointerDownCapture,p=>{const y=p.target.getBoundingClientRect(),b=p.clientX-y.left,S=p.clientY-y.top;s.onThumbPointerDown({x:b,y:S})}),onPointerUp:de(e.onPointerUp,s.onThumbPointerUp)}))}),P5="ScrollAreaCorner",_Y=d.forwardRef((e,t)=>{const n=qr(P5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?d.createElement(EY,Y({},e,{ref:t})):null}),EY=d.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(P5,n),[i,s]=d.useState(0),[l,u]=d.useState(0),f=!!(i&&l);return fc(o.scrollbarX,()=>{var m;const p=((m=o.scrollbarX)===null||m===void 0?void 0:m.offsetHeight)||0;o.onCornerHeightChange(p),u(p)}),fc(o.scrollbarY,()=>{var m;const p=((m=o.scrollbarY)===null||m===void 0?void 0:m.offsetWidth)||0;o.onCornerWidthChange(p),s(p)}),f?d.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function Vp(e){return e?parseInt(e,10):0}function A5(e,t){const n=e/t;return isNaN(n)?0:n}function ig(e){const t=A5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function CY(e,t,n,r="ltr"){const o=ig(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,f=n.scrollbar.size-n.scrollbar.paddingEnd-l,m=n.content-n.viewport,p=r==="ltr"?[0,m]:[m*-1,0];return M5([u,f],p)(e)}function y2(e,t,n="ltr"){const r=ig(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],f=fd(e,u);return M5([0,s],[0,l])(f)}function M5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function O5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function sg(e,t){const n=Ft(e),r=d.useRef(0);return d.useEffect(()=>()=>window.clearTimeout(r.current),[]),d.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function fc(e,t){const n=Ft(t);An(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const N5=hY,RY=mY,kY=_Y,ag=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(N5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx(RY,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(D5,{}),v.jsx(kY,{})]}));ag.displayName=N5.displayName;const D5=d.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx($5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(bY,{className:"relative flex-1 rounded-full bg-border"})}));D5.displayName=$5.displayName;const I5="Name",L5="Created time",F5="Modified time",w2="input",TY="output",x2={[Es.NAME]:I5,[Es.CTIME]:L5,[Es.MTIME]:F5};function PY(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=OP(!1),[i,s]=bt(W=>[W.fileManagerState,W.updateFileManagerState]),{toast:l}=Id(),[u,f]=d.useState(0),[m,p]=d.useState(0),g=d.useRef(null),y=lV(i.searchText,300),[b,S]=d.useState(w2),[E,_]=d.useState([]),[x,C]=d.useState([]),[R,P]=d.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let W=R;R>0&&(W=R-1),P(W),t(b,x[W].name)},[R,x]),Zn("right",()=>{let W=R;R{r||p(u)},[r,u]);const M=d.useCallback(W=>{W!==null&&r&&setTimeout(()=>{W.scrollTo({top:m,left:0})},100)},[r,m]);d.useEffect(()=>{(async()=>{try{const q=await Wj(b);_(q)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[b]),d.useEffect(()=>{if(!r)return;(async()=>{try{let q=E;y&&(q=new kc(q,{keys:["name"]}).search(y).map(F=>q[F.refIndex])),q=xH.orderBy(q,i.sortBy,i.sortOrder);const X=q.map(ae=>{const V=n,F=ae.height*(V/ae.width);return{src:`${Ls}/media_thumbnail_file?tab=${b}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(V)}&height=${Math.ceil(F)}`,height:F,width:V,name:ae.name}});C(X)}catch(q){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:q.message?q.message:q.toString()})}})()},[E,y,i,n,r]);const A=W=>{f(W.currentTarget.scrollTop)},D=({index:W})=>{o(),P(W),t(b,x[W].name)},U=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${x.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(yn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(yn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(fz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Jm,{open:r,onOpenChange:o,children:[v.jsx(fP,{asChild:!0,children:v.jsx(yn,{tooltip:"File Manager",children:v.jsx(eV,{})})}),v.jsxs(Hd,{className:"h-4/5 max-w-6xl",children:[v.jsx(Kd,{children:U()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(lz,{className:"absolute left-[8px]"}),v.jsx(Ld,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:W=>{W.preventDefault(),W.stopPropagation();const q=W.target;s({searchText:q.value})},placeholder:"Search by file name"})]}),v.jsx(a5,{defaultValue:b,onValueChange:W=>S(W),children:v.jsxs(jx,{"aria-label":"Manage your account",children:[v.jsx(pa,{value:w2,children:"Image Directory"}),v.jsx(pa,{value:TY,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(Uo,{value:x2[i.sortBy],onValueChange:W=>{switch(W){case I5:s({sortBy:Es.NAME});break;case L5:s({sortBy:Es.CTIME});break;case F5:s({sortBy:Es.MTIME});break}},children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{})}),v.jsx(vo,{children:Object.values(x2).map(W=>v.jsx(yo,{value:W,children:W},W))})]}),i.sortOrder===Ou.DESCENDING?v.jsx(yn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:Ou.ASCENDING})},children:v.jsx(iK,{})}):v.jsx(yn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:Ou.DESCENDING})},children:v.jsx(lK,{})})]})})]}),v.jsx(ag,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(nK,{layout:i.layout,photos:x,spacing:12,padding:0,onClick:D})})]})]})}var Yd=e=>e.type==="checkbox",$l=e=>e instanceof Date,Fn=e=>e==null;const j5=e=>typeof e=="object";var sn=e=>!Fn(e)&&!Array.isArray(e)&&j5(e)&&!$l(e),z5=e=>sn(e)&&e.target?Yd(e.target)?e.target.checked:e.target.value:e,AY=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,B5=(e,t)=>e.has(AY(t)),MY=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Wx=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Wx&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!MY(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Xd=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Xd(t.split(/[,[\].]+?/)).reduce((o,i)=>Fn(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},Fo=e=>typeof e=="boolean";const Wp={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},ui={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},U5=Fe.createContext(null),lg=()=>Fe.useContext(U5),OY=e=>{const{children:t,...n}=e;return Fe.createElement(U5.Provider,{value:n},t)};var V5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,W5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},ep=e=>Array.isArray(e)?e:[e],H5=(e,t,n)=>!e||!t||e===t||ep(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Hx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function NY(e){const t=lg(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),f=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),m=Fe.useRef(o);return m.current=o,Hx({disabled:r,next:p=>u.current&&H5(m.current,p.name,i)&&W5(p,f.current,n._updateFormState)&&l({...n._formState,...p}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,f.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),V5(s,n,f.current,!1)}var Wo=e=>typeof e=="string",K5=(e,t,n,r,o)=>Wo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function DY(e){const t=lg(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Hx({disabled:i,subject:n._subjects.values,next:m=>{H5(l.current,m.name,s)&&f(so(K5(l.current,n._names,m.values||n._formValues,!1,o)))}});const[u,f]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Kx=e=>/^\w*$/.test(e),G5=e=>Xd(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Kx(t)?[t]:G5(t),i=o.length,s=i-1;for(;++r{const m=o._options.shouldUnregister||i,p=(g,y)=>{const b=ve(o._fields,g);b&&(b._f.mount=y)};if(p(n,!0),m){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?m&&!o._state.action:m)?o.unregister(n):p(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...Fo(r)||Fo(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(m=>f.current.onChange({target:{value:z5(m),name:n},type:Wp.CHANGE}),[n]),onBlur:Fe.useCallback(()=>f.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Wp.BLUR}),[n,o]),ref:m=>{const p=ve(o._fields,n);p&&m&&(p._f.ref={focus:()=>m.focus(),select:()=>m.select(),setCustomValidity:g=>m.setCustomValidity(g),reportValidity:()=>m.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const LY=e=>e.render(IY(e));var Y5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},b2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),S2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const tp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&tp(l,t)}}};var FY=(e,t,n)=>{const r=Xd(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Gx=e=>e.type==="file",ms=e=>typeof e=="function",Hp=e=>{if(!Wx)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},np=e=>Wo(e),Yx=e=>e.type==="radio",Kp=e=>e instanceof RegExp;const _2={value:!1,isValid:!1},E2={value:!0,isValid:!0};var X5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?E2:{value:e[0].value,isValid:!0}:E2:_2}return _2};const C2={isValid:!1,value:null};var Z5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,C2):C2;function $2(e,t,n="validate"){if(np(e)||Array.isArray(e)&&e.every(np)||Fo(e)&&!e)return{type:n,message:np(e)?e:"",ref:t}}var sl=e=>sn(e)&&!Kp(e)?e:{value:e,message:""},R2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:f,min:m,max:p,pattern:g,validate:y,name:b,valueAsNumber:S,mount:E,disabled:_}=e._f,x=ve(t,b);if(!E||_)return{};const C=s?s[0]:i,R=X=>{r&&C.reportValidity&&(C.setCustomValidity(Fo(X)?"":X||""),C.reportValidity())},P={},M=Yx(i),A=Yd(i),D=M||A,U=(S||Gx(i))&&Ht(i.value)&&Ht(x)||Hp(i)&&i.value===""||x===""||Array.isArray(x)&&!x.length,W=Y5.bind(null,b,n,P),q=(X,ae,V,F=ui.maxLength,N=ui.minLength)=>{const ie=X?ae:V;P[b]={type:X?F:N,message:ie,ref:i,...W(X?F:N,ie)}};if(o?!Array.isArray(x)||!x.length:l&&(!D&&(U||Fn(x))||Fo(x)&&!x||A&&!X5(s).isValid||M&&!Z5(s).isValid)){const{value:X,message:ae}=np(l)?{value:!!l,message:l}:sl(l);if(X&&(P[b]={type:ui.required,message:ae,ref:C,...W(ui.required,ae)},!n))return R(ae),P}if(!U&&(!Fn(m)||!Fn(p))){let X,ae;const V=sl(p),F=sl(m);if(!Fn(x)&&!isNaN(x)){const N=i.valueAsNumber||x&&+x;Fn(V.value)||(X=N>V.value),Fn(F.value)||(ae=Nnew Date(new Date().toDateString()+" "+H),K=i.type=="time",Z=i.type=="week";Wo(V.value)&&x&&(X=K?ie(x)>ie(V.value):Z?x>V.value:N>new Date(V.value)),Wo(F.value)&&x&&(ae=K?ie(x)+X.value,F=!Fn(ae.value)&&x.length<+ae.value;if((V||F)&&(q(V,X.message,ae.message),!n))return R(P[b].message),P}if(g&&!U&&Wo(x)){const{value:X,message:ae}=sl(g);if(Kp(X)&&!x.match(X)&&(P[b]={type:ui.pattern,message:ae,ref:i,...W(ui.pattern,ae)},!n))return R(ae),P}if(y){if(ms(y)){const X=await y(x,t),ae=$2(X,C);if(ae&&(P[b]={...ae,...W(ui.validate,ae.message)},!n))return R(ae.message),P}else if(sn(y)){let X={};for(const ae in y){if(!Fr(X)&&!n)break;const V=$2(await y[ae](x,t),C,ae);V&&(X={...V,...W(ae,V.message)},R(V.message),n&&(P[b]=X))}if(!Fr(X)&&(P[b]={ref:C,...X},!n))return P}}return R(!0),P};function jY(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Gp=e=>Fn(e)||!j5(e);function ma(e,t){if(Gp(e)||Gp(t))return e===t;if($l(e)&&$l(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if($l(i)&&$l(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ma(i,s):i!==s)return!1}}return!0}var q5=e=>e.type==="select-multiple",BY=e=>Yx(e)||Yd(e),N0=e=>Hp(e)&&e.isConnected,Q5=e=>{for(const t in e)if(ms(e[t]))return!0;return!1};function Yp(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Q5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Yp(e[r],t[r])):Fn(e[r])||(t[r]=!0);return t}function J5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Q5(e[o])?Ht(t)||Gp(n[o])?n[o]=Array.isArray(e[o])?Yp(e[o],[]):{...Yp(e[o])}:J5(e[o],Fn(t)?{}:t[o],n[o]):n[o]=!ma(e[o],t[o]);return n}var D0=(e,t)=>J5(e,t,Yp(t)),e3=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Wo(e)?new Date(e):r?r(e):e;function I0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Gx(t)?t.files:Yx(t)?Z5(e.refs).value:q5(t)?[...t.selectedOptions].map(({value:n})=>n):Yd(t)?X5(e.refs).value:e3(Ht(t.value)?e.ref.value:t.value,e)}var UY=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},du=e=>Ht(e)?e:Kp(e)?e.source:sn(e)?Kp(e.value)?e.value.source:e.value:e,VY=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function k2(e,t,n){const r=ve(e,n);if(r||Kx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var WY=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,HY=(e,t)=>!Xd(ve(e,t)).length&&pn(e,t);const KY={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function GY(e={},t){let n={...KY,...e},r={submitCount:0,isDirty:!1,isLoading:ms(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},f,m=0;const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:O0(),array:O0(),state:O0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,b=b2(n.mode),S=b2(n.reValidateMode),E=n.criteriaMode===mo.all,_=L=>Q=>{clearTimeout(m),m=setTimeout(L,Q)},x=async L=>{if(p.isValid||L){const Q=n.resolver?Fr((await U()).errors):await q(o,!0);Q!==r.isValid&&g.state.next({isValid:Q})}},C=L=>p.isValidating&&g.state.next({isValidating:L}),R=(L,Q=[],J,we,me=!0,fe=!0)=>{if(we&&J){if(l.action=!0,fe&&Array.isArray(ve(o,L))){const Re=J(ve(o,L),we.argA,we.argB);me&&wt(o,L,Re)}if(fe&&Array.isArray(ve(r.errors,L))){const Re=J(ve(r.errors,L),we.argA,we.argB);me&&wt(r.errors,L,Re),HY(r.errors,L)}if(p.touchedFields&&fe&&Array.isArray(ve(r.touchedFields,L))){const Re=J(ve(r.touchedFields,L),we.argA,we.argB);me&&wt(r.touchedFields,L,Re)}p.dirtyFields&&(r.dirtyFields=D0(i,s)),g.state.next({name:L,isDirty:ae(L,Q),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,L,Q)},P=(L,Q)=>{wt(r.errors,L,Q),g.state.next({errors:r.errors})},M=(L,Q,J,we)=>{const me=ve(o,L);if(me){const fe=ve(s,L,Ht(J)?ve(i,L):J);Ht(fe)||we&&we.defaultChecked||Q?wt(s,L,Q?fe:I0(me._f)):N(L,fe),l.mount&&x()}},A=(L,Q,J,we,me)=>{let fe=!1,Re=!1;const ft={name:L};if(!J||we){p.isDirty&&(Re=r.isDirty,r.isDirty=ft.isDirty=ae(),fe=Re!==ft.isDirty);const ht=ma(ve(i,L),Q);Re=ve(r.dirtyFields,L),ht?pn(r.dirtyFields,L):wt(r.dirtyFields,L,!0),ft.dirtyFields=r.dirtyFields,fe=fe||p.dirtyFields&&Re!==!ht}if(J){const ht=ve(r.touchedFields,L);ht||(wt(r.touchedFields,L,J),ft.touchedFields=r.touchedFields,fe=fe||p.touchedFields&&ht!==J)}return fe&&me&&g.state.next(ft),fe?ft:{}},D=(L,Q,J,we)=>{const me=ve(r.errors,L),fe=p.isValid&&Fo(Q)&&r.isValid!==Q;if(e.delayError&&J?(f=_(()=>P(L,J)),f(e.delayError)):(clearTimeout(m),f=null,J?wt(r.errors,L,J):pn(r.errors,L)),(J?!ma(me,J):me)||!Fr(we)||fe){const Re={...we,...fe&&Fo(Q)?{isValid:Q}:{},errors:r.errors,name:L};r={...r,...Re},g.state.next(Re)}C(!1)},U=async L=>n.resolver(s,n.context,UY(L||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),W=async L=>{const{errors:Q}=await U(L);if(L)for(const J of L){const we=ve(Q,J);we?wt(r.errors,J,we):pn(r.errors,J)}else r.errors=Q;return Q},q=async(L,Q,J={valid:!0})=>{for(const we in L){const me=L[we];if(me){const{_f:fe,...Re}=me;if(fe){const ft=u.array.has(fe.name),ht=await R2(me,s,E,n.shouldUseNativeValidation&&!Q,ft);if(ht[fe.name]&&(J.valid=!1,Q))break;!Q&&(ve(ht,fe.name)?ft?FY(r.errors,ht,fe.name):wt(r.errors,fe.name,ht[fe.name]):pn(r.errors,fe.name))}Re&&await q(Re,Q,J)}}return J.valid},X=()=>{for(const L of u.unMount){const Q=ve(o,L);Q&&(Q._f.refs?Q._f.refs.every(J=>!N0(J)):!N0(Q._f.ref))&&he(L)}u.unMount=new Set},ae=(L,Q)=>(L&&Q&&wt(s,L,Q),!ma(ce(),i)),V=(L,Q,J)=>K5(L,u,{...l.mount?s:Ht(Q)?i:Wo(L)?{[L]:Q}:Q},J,Q),F=L=>Xd(ve(l.mount?s:i,L,e.shouldUnregister?ve(i,L,[]):[])),N=(L,Q,J={})=>{const we=ve(o,L);let me=Q;if(we){const fe=we._f;fe&&(!fe.disabled&&wt(s,L,e3(Q,fe)),me=Hp(fe.ref)&&Fn(Q)?"":Q,q5(fe.ref)?[...fe.ref.options].forEach(Re=>Re.selected=me.includes(Re.value)):fe.refs?Yd(fe.ref)?fe.refs.length>1?fe.refs.forEach(Re=>(!Re.defaultChecked||!Re.disabled)&&(Re.checked=Array.isArray(me)?!!me.find(ft=>ft===Re.value):me===Re.value)):fe.refs[0]&&(fe.refs[0].checked=!!me):fe.refs.forEach(Re=>Re.checked=Re.value===me):Gx(fe.ref)?fe.ref.value="":(fe.ref.value=me,fe.ref.type||g.values.next({name:L,values:{...s}})))}(J.shouldDirty||J.shouldTouch)&&A(L,me,J.shouldTouch,J.shouldDirty,!0),J.shouldValidate&&se(L)},ie=(L,Q,J)=>{for(const we in Q){const me=Q[we],fe=`${L}.${we}`,Re=ve(o,fe);(u.array.has(L)||!Gp(me)||Re&&!Re._f)&&!$l(me)?ie(fe,me,J):N(fe,me,J)}},K=(L,Q,J={})=>{const we=ve(o,L),me=u.array.has(L),fe=so(Q);wt(s,L,fe),me?(g.array.next({name:L,values:{...s}}),(p.isDirty||p.dirtyFields)&&J.shouldDirty&&g.state.next({name:L,dirtyFields:D0(i,s),isDirty:ae(L,fe)})):we&&!we._f&&!Fn(fe)?ie(L,fe,J):N(L,fe,J),S2(L,u)&&g.state.next({...r}),g.values.next({name:L,values:{...s}}),!l.mount&&t()},Z=async L=>{const Q=L.target;let J=Q.name,we=!0;const me=ve(o,J),fe=()=>Q.type?I0(me._f):z5(L),Re=ft=>{we=Number.isNaN(ft)||ft===ve(s,J,ft)};if(me){let ft,ht;const _n=fe(),Cr=L.type===Wp.BLUR||L.type===Wp.FOCUS_OUT,Ni=!VY(me._f)&&!n.resolver&&!ve(r.errors,J)&&!me._f.deps||WY(Cr,ve(r.touchedFields,J),r.isSubmitted,S,b),Co=S2(J,u,Cr);wt(s,J,_n),Cr?(me._f.onBlur&&me._f.onBlur(L),f&&f(0)):me._f.onChange&&me._f.onChange(L);const Vn=A(J,_n,Cr,!1),Ba=!Fr(Vn)||Co;if(!Cr&&g.values.next({name:J,type:L.type,values:{...s}}),Ni)return p.isValid&&x(),Ba&&g.state.next({name:J,...Co?{}:Vn});if(!Cr&&Co&&g.state.next({...r}),C(!0),n.resolver){const{errors:Di}=await U([J]);if(Re(_n),we){const Ws=k2(r.errors,o,J),Ii=k2(Di,o,Ws.name||J);ft=Ii.error,J=Ii.name,ht=Fr(Di)}}else ft=(await R2(me,s,E,n.shouldUseNativeValidation))[J],Re(_n),we&&(ft?ht=!1:p.isValid&&(ht=await q(o,!0)));we&&(me._f.deps&&se(me._f.deps),D(J,ht,ft,Vn))}},H=(L,Q)=>{if(ve(r.errors,Q)&&L.focus)return L.focus(),1},se=async(L,Q={})=>{let J,we;const me=ep(L);if(C(!0),n.resolver){const fe=await W(Ht(L)?L:me);J=Fr(fe),we=L?!me.some(Re=>ve(fe,Re)):J}else L?(we=(await Promise.all(me.map(async fe=>{const Re=ve(o,fe);return await q(Re&&Re._f?{[fe]:Re}:Re)}))).every(Boolean),!(!we&&!r.isValid)&&x()):we=J=await q(o);return g.state.next({...!Wo(L)||p.isValid&&J!==r.isValid?{}:{name:L},...n.resolver||!L?{isValid:J}:{},errors:r.errors,isValidating:!1}),Q.shouldFocus&&!we&&tp(o,H,L?me:u.mount),we},ce=L=>{const Q={...i,...l.mount?s:{}};return Ht(L)?Q:Wo(L)?ve(Q,L):L.map(J=>ve(Q,J))},Ve=(L,Q)=>({invalid:!!ve((Q||r).errors,L),isDirty:!!ve((Q||r).dirtyFields,L),isTouched:!!ve((Q||r).touchedFields,L),error:ve((Q||r).errors,L)}),Ue=L=>{L&&ep(L).forEach(Q=>pn(r.errors,Q)),g.state.next({errors:L?r.errors:{}})},We=(L,Q,J)=>{const we=(ve(o,L,{_f:{}})._f||{}).ref;wt(r.errors,L,{...Q,ref:we}),g.state.next({name:L,errors:r.errors,isValid:!1}),J&&J.shouldFocus&&we&&we.focus&&we.focus()},Oe=(L,Q)=>ms(L)?g.values.subscribe({next:J=>L(V(void 0,Q),J)}):V(L,Q,!0),he=(L,Q={})=>{for(const J of L?ep(L):u.mount)u.mount.delete(J),u.array.delete(J),Q.keepValue||(pn(o,J),pn(s,J)),!Q.keepError&&pn(r.errors,J),!Q.keepDirty&&pn(r.dirtyFields,J),!Q.keepTouched&&pn(r.touchedFields,J),!n.shouldUnregister&&!Q.keepDefaultValue&&pn(i,J);g.values.next({values:{...s}}),g.state.next({...r,...Q.keepDirty?{isDirty:ae()}:{}}),!Q.keepIsValid&&x()},xe=({disabled:L,name:Q,field:J,fields:we,value:me})=>{if(Fo(L)){const fe=L?void 0:Ht(me)?I0(J?J._f:ve(we,Q)._f):me;wt(s,Q,fe),A(Q,fe,!1,!1,!0)}},$e=(L,Q={})=>{let J=ve(o,L);const we=Fo(Q.disabled);return wt(o,L,{...J||{},_f:{...J&&J._f?J._f:{ref:{name:L}},name:L,mount:!0,...Q}}),u.mount.add(L),J?xe({field:J,disabled:Q.disabled,name:L}):M(L,!0,Q.value),{...we?{disabled:Q.disabled}:{},...n.progressive?{required:!!Q.required,min:du(Q.min),max:du(Q.max),minLength:du(Q.minLength),maxLength:du(Q.maxLength),pattern:du(Q.pattern)}:{},name:L,onChange:Z,onBlur:Z,ref:me=>{if(me){$e(L,Q),J=ve(o,L);const fe=Ht(me.value)&&me.querySelectorAll&&me.querySelectorAll("input,select,textarea")[0]||me,Re=BY(fe),ft=J._f.refs||[];if(Re?ft.find(ht=>ht===fe):fe===J._f.ref)return;wt(o,L,{_f:{...J._f,...Re?{refs:[...ft.filter(N0),fe,...Array.isArray(ve(i,L))?[{}]:[]],ref:{type:fe.type,name:L}}:{ref:fe}}}),M(L,!1,void 0,fe)}else J=ve(o,L,{}),J._f&&(J._f.mount=!1),(n.shouldUnregister||Q.shouldUnregister)&&!(B5(u.array,L)&&l.action)&&u.unMount.add(L)}}},Ae=()=>n.shouldFocusError&&tp(o,H,u.mount),Me=L=>{Fo(L)&&(g.state.next({disabled:L}),tp(o,Q=>{Q.disabled=L},0,!1))},je=(L,Q)=>async J=>{J&&(J.preventDefault&&J.preventDefault(),J.persist&&J.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:me,values:fe}=await U();r.errors=me,we=fe}else await q(o);pn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await L(we,J)):(Q&&await Q({...r.errors},J),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Mt=(L,Q={})=>{ve(o,L)&&(Ht(Q.defaultValue)?K(L,ve(i,L)):(K(L,Q.defaultValue),wt(i,L,Q.defaultValue)),Q.keepTouched||pn(r.touchedFields,L),Q.keepDirty||(pn(r.dirtyFields,L),r.isDirty=Q.defaultValue?ae(L,ve(i,L)):ae()),Q.keepError||(pn(r.errors,L),p.isValid&&x()),g.state.next({...r}))},ct=(L,Q={})=>{const J=L?so(L):i,we=so(J),me=L&&!Fr(L)?we:i;if(Q.keepDefaultValues||(i=J),!Q.keepValues){if(Q.keepDirtyValues||y)for(const fe of u.mount)ve(r.dirtyFields,fe)?wt(me,fe,ve(s,fe)):K(fe,ve(me,fe));else{if(Wx&&Ht(L))for(const fe of u.mount){const Re=ve(o,fe);if(Re&&Re._f){const ft=Array.isArray(Re._f.refs)?Re._f.refs[0]:Re._f.ref;if(Hp(ft)){const ht=ft.closest("form");if(ht){ht.reset();break}}}}o={}}s=e.shouldUnregister?Q.keepDefaultValues?so(i):{}:so(me),g.array.next({values:{...me}}),g.values.next({values:{...me}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!p.isValid||!!Q.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:Q.keepSubmitCount?r.submitCount:0,isDirty:Q.keepDirty?r.isDirty:!!(Q.keepDefaultValues&&!ma(L,i)),isSubmitted:Q.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Q.keepDirtyValues?r.dirtyFields:Q.keepDefaultValues&&L?D0(i,L):{},touchedFields:Q.keepTouched?r.touchedFields:{},errors:Q.keepErrors?r.errors:{},isSubmitSuccessful:Q.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(L,Q)=>ct(ms(L)?L(s):L,Q);return{control:{register:$e,unregister:he,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:U,_getWatch:V,_getDirty:ae,_updateValid:x,_removeUnmounted:X,_updateFieldArray:R,_updateDisabledField:xe,_getFieldArray:F,_reset:ct,_resetDefaultValues:()=>ms(n.defaultValues)&&n.defaultValues().then(L=>{Kt(L,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:L=>{r={...r,...L}},_disableForm:Me,_subjects:g,_proxyFormState:p,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(L){l=L},get _defaultValues(){return i},get _names(){return u},set _names(L){u=L},get _formState(){return r},set _formState(L){r=L},get _options(){return n},set _options(L){n={...n,...L}}},trigger:se,register:$e,handleSubmit:je,watch:Oe,setValue:K,getValues:ce,reset:Kt,resetField:Mt,clearErrors:Ue,unregister:he,setError:We,setFocus:(L,Q={})=>{const J=ve(o,L),we=J&&J._f;if(we){const me=we.refs?we.refs[0]:we.ref;me.focus&&(me.focus(),Q.shouldSelect&&me.select())}},getFieldState:Ve}}function YY(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ms(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ms(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...GY(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Hx({subject:i._subjects.state,next:s=>{W5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ma(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=V5(r,i),t.current}var T2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},t3=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?T2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return T2(s,o,e)})};for(var r in t.fields)n(r)},XY=function(e,t){t.shouldUseNativeValidation&&t3(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(qY(t.names||Object.keys(e),r)){var s=Object.assign({},ZY(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},ZY=function(e){return Array.isArray(e)?e.filter(Boolean):[]},qY=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},QY=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(p){return e.push(p)})}),t){var u=n[s].types,f=u&&u[r.code];n[s]=Y5(s,t,n,o,f?[].concat(f,r.message):r.message)}e.shift()}return n},JY=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(f){return i.shouldUseNativeValidation&&t3({},i),{errors:{},values:n.raw?r:f}})}catch(f){return l(f)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:XY(QY(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var P2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(P2||(P2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ca=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Go extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Go.create=e=>new Go(e);const Xp=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let eX=Xp;function C1(){return eX}const $1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(f=>!!f).slice().reverse();for(const f of u)l=f(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=$1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,C1(),Xp].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),tX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),A2=e=>e.status==="aborted",M2=e=>e.status==="dirty",Zp=e=>e.status==="valid",R1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Qo{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const O2=(e,t)=>{if(Zp(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Go(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ca(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ca(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(R1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},i=this._parseSync({data:t,path:o.path,parent:o});return O2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ca(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(R1(o)?o:Promise.resolve(o));return O2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Pi({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return Cs.create(this,this._def)}nullable(){return gc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Yo.create(this,this._def)}promise(){return pd.create(this,this._def)}or(t){return Jp.create([this,t],this._def)}and(t){return em.create(this,t,this._def)}transform(t){return new Pi({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new im({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new hX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new N1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return cg.create(this,t)}readonly(){return I1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const nX=/^c[^\s-]{8,}$/i,rX=/^[a-z][a-z0-9]*$/,oX=/^[0-9A-HJKMNP-TV-Z]{26}$/,iX=/^[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,sX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let L0;const lX=/^(((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}))$/,cX=/^(([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})))$/,uX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function dX(e,t){return!!((t==="v4"||!t)&&lX.test(e)||(t==="v6"||!t)&&cX.test(e))}class yi extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new yi({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new yi({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yi({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new yi({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function fX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class hc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?fX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new hc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new hc({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew hc({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class pc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new pc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new pc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new pc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class k1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class hd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new hd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew hd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodSymbol,...Xe(e)});class qp extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}qp.create=e=>new qp({typeName:ze.ZodUndefined,...Xe(e)});class Qp extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Qp.create=e=>new Qp({typeName:ze.ZodNull,...Xe(e)});class P1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}P1.create=e=>new P1({typeName:ze.ZodAny,...Xe(e)});class Dl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Dl.create=e=>new Dl({typeName:ze.ZodUnknown,...Xe(e)});class Ms extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Ms.create=e=>new Ms({typeName:ze.ZodNever,...Xe(e)});class A1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}A1.create=e=>new A1({typeName:ze.ZodVoid,...Xe(e)});class Yo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Qo(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Qo(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Yo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Yo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Yo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Yo.create=(e,t)=>new Yo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function dl(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=Cs.create(dl(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Yo?new Yo({...e._def,type:dl(e.element)}):e instanceof Cs?Cs.create(dl(e.unwrap())):e instanceof gc?gc.create(dl(e.unwrap())):e instanceof Ti?Ti.create(e.items.map(t=>dl(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const f=this._getOrReturnCtx(t);return Ee(f,{code:pe.invalid_type,expected:be.object,received:f.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Ms&&this._def.unknownKeys==="strip"))for(const f in o.data)s.includes(f)||l.push(f);const u=[];for(const f of s){const m=i[f],p=o.data[f];u.push({key:{status:"valid",value:f},value:m._parse(new Qo(o,p,o.path,f)),alwaysSet:f in o.data})}if(this._def.catchall instanceof Ms){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of l)u.push({key:{status:"valid",value:m},value:{status:"valid",value:o.data[m]}});else if(f==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of l){const p=o.data[m];u.push({key:{status:"valid",value:m},value:f._parse(new Qo(o,p,o.path,m)),alwaysSet:m in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of u){const p=await m.key;f.push({key:p,value:await m.value,alwaysSet:m.alwaysSet})}return f}).then(f=>zn.mergeObjectSync(r,f)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return dl(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Cs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return n3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Ms.create(),typeName:ze.ZodObject,...Xe(t)});class Jp extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Go(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=u._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&s.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Go(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Jp.create=(e,t)=>new Jp({options:e,typeName:ze.ZodUnion,...Xe(t)});const rp=e=>e instanceof nm?rp(e.schema):e instanceof Pi?rp(e.innerType()):e instanceof rm?[e.value]:e instanceof Da?e.options:e instanceof om?Object.keys(e.enum):e instanceof im?rp(e._def.innerType):e instanceof qp?[void 0]:e instanceof Qp?[null]:null;class Xx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=rp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Xx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function M1(e,t){const n=ca(e),r=ca(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=M1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(A2(i)||A2(s))return Ze;const l=M1(i.value,s.value);return l.valid?((M2(i)||M2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}em.create=(e,t,n)=>new em({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class Ti extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Qo(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new Ti({...this._def,rest:t})}}Ti.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ti({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class tm extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Qo(r,l,r.path,l)),value:s._parse(new Qo(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new tm({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new tm({keyType:yi.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class O1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],f)=>({key:o._parse(new Qo(r,l,r.path,[f,"key"])),value:i._parse(new Qo(r,u,r.path,[f,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const f=await u.key,m=await u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const f=u.key,m=u.value;if(f.status==="aborted"||m.status==="aborted")return Ze;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),l.set(f.value,m.value)}return{status:n.value,value:l}}}}O1.create=(e,t,n)=>new O1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class mc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const f=new Set;for(const m of u){if(m.status==="aborted")return Ze;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const l=[...r.data.values()].map((u,f)=>i._parse(new Qo(r,u,r.path,f)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new mc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new mc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}mc.create=(e,t)=>new mc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Lu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return $1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,C1(),Xp].filter(f=>!!f),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof pd){const l=this;return rr(async function(...u){const f=new Go([]),m=await l._def.args.parseAsync(u,i).catch(y=>{throw f.addIssue(r(u,y)),f}),p=await Reflect.apply(s,this,m);return await l._def.returns._def.type.parseAsync(p,i).catch(y=>{throw f.addIssue(o(p,y)),f})})}else{const l=this;return rr(function(...u){const f=l._def.args.safeParse(u,i);if(!f.success)throw new Go([r(u,f.error)]);const m=Reflect.apply(s,this,f.data),p=l._def.returns.safeParse(m,i);if(!p.success)throw new Go([o(m,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Lu({...this._def,args:Ti.create(t).rest(Dl.create())})}returns(t){return new Lu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Lu({args:t||Ti.create([]).rest(Dl.create()),returns:n||Dl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class nm extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}nm.create=(e,t)=>new nm({getter:e,typeName:ze.ZodLazy,...Xe(t)});class rm extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}rm.create=(e,t)=>new rm({value:e,typeName:ze.ZodLiteral,...Xe(t)});function n3(e,t){return new Da({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Da extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Da.create(t)}exclude(t){return Da.create(this.options.filter(n=>!t.includes(n)))}}Da.create=n3;class om extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}om.create=(e,t)=>new om({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class pd extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}pd.create=(e,t)=>new pd({type:e,typeName:ze.ZodPromise,...Xe(t)});class Pi extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Zp(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Zp(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Pi.create=(e,t,n)=>new Pi({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Pi.createWithPreprocess=(e,t,n)=>new Pi({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class Cs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Cs.create=(e,t)=>new Cs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class gc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}gc.create=(e,t)=>new gc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class im extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}im.create=(e,t)=>new im({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class N1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return R1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Go(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class D1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}D1.create=e=>new D1({typeName:ze.ZodNaN,...Xe(e)});class hX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class cg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),tX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new cg({in:t,out:n,typeName:ze.ZodPipeline})}}class I1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Zp(n)&&(n.value=Object.freeze(n.value)),n}}I1.create=(e,t)=>new I1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const fu=yi.create;hc.create;D1.create;pc.create;const hu=k1.create;hd.create;T1.create;qp.create;Qp.create;P1.create;Dl.create;Ms.create;A1.create;Yo.create;const pX=Vt.create;Vt.strictCreate;Jp.create;Xx.create;em.create;Ti.create;tm.create;O1.create;mc.create;Lu.create;nm.create;rm.create;Da.create;om.create;pd.create;Pi.create;Cs.create;gc.create;Pi.createWithPreprocess;cg.create;const L1="horizontal",mX=["horizontal","vertical"],r3=d.forwardRef((e,t)=>{const{decorative:n,orientation:r=L1,...o}=e,i=o3(r)?r:L1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return d.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});r3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!o3(r)?new Error(gX(o,n)):null}};function gX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${L1}\`.`}function o3(e){return mX.includes(e)}const i3=r3,gn=d.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(i3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));gn.displayName=i3.displayName;const vX=d.forwardRef((e,t)=>d.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),s3=vX,yX=Dm("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Zx=d.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(s3,{ref:r,className:Ce(yX(),e,t?"opacity-50":"","select-none"),...n}));Zx.displayName=s3.displayName;const wX=OY,a3=d.createContext({}),al=({...e})=>v.jsx(a3.Provider,{value:{name:e.name},children:v.jsx(LY,{...e})}),ug=()=>{const e=d.useContext(a3),t=d.useContext(l3),{getFieldState:n,formState:r}=lg(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},l3=d.createContext({}),oa=d.forwardRef(({className:e,...t},n)=>{const r=d.useId();return v.jsx(l3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});oa.displayName="FormItem";const ia=d.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ug();return v.jsx(Zx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});ia.displayName="FormLabel";const sa=d.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ug();return v.jsx(Zo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});sa.displayName="FormControl";const aa=d.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ug();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});aa.displayName="FormDescription";const xX=d.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ug(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});xX.displayName="FormMessage";const c3="Switch",[bX,_te]=Mn(c3),[SX,_X]=bX(c3),EX=d.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:f,...m}=e,[p,g]=d.useState(null),y=Be(t,x=>g(x)),b=d.useRef(!1),S=p?!!p.closest("form"):!0,[E=!1,_]=Zr({prop:o,defaultProp:i,onChange:f});return d.createElement(SX,{scope:n,checked:E,disabled:l},d.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":E,"aria-required":s,"data-state":u3(E),"data-disabled":l?"":void 0,disabled:l,value:u},m,{ref:y,onClick:de(e.onClick,x=>{_(C=>!C),S&&(b.current=x.isPropagationStopped(),b.current||x.stopPropagation())})})),S&&d.createElement(RX,{control:p,bubbles:!b.current,name:r,value:u,checked:E,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),CX="SwitchThumb",$X=d.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(CX,n);return d.createElement(Pe.span,Y({"data-state":u3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),RX=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=d.useRef(null),s=zx(n),l=yx(t);return d.useEffect(()=>{const u=i.current,f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(s!==n&&p){const g=new Event("click",{bubbles:r});p.call(u,n),u.dispatchEvent(g)}},[s,n,r]),d.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function u3(e){return e?"checked":"unchecked"}const d3=EX,kX=$X,co=d.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=d3.displayName;const TX="AlertDialog",[PX,Ete]=Mn(TX,[dP]),zs=dP(),AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement(Cx,Y({},r,n,{modal:!0}))},MX=e=>{const{__scopeAlertDialog:t,...n}=e,r=zs(t);return d.createElement($x,Y({},r,n))},OX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Bd,Y({},o,r,{ref:t}))}),f3="AlertDialogContent",[NX,DX]=PX(f3),IX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=zs(n),s=d.useRef(null),l=Be(t,s),u=d.useRef(null);return d.createElement(hW,{contentName:f3,titleName:LX,docsSlug:"alert-dialog"},d.createElement(NX,{scope:n,cancelRef:u},d.createElement(Ud,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:de(o.onOpenAutoFocus,f=>{var m;f.preventDefault(),(m=u.current)===null||m===void 0||m.focus({preventScroll:!0})}),onPointerDownOutside:f=>f.preventDefault(),onInteractOutside:f=>f.preventDefault()}),d.createElement(lx,null,r),!1)))}),LX="AlertDialogTitle",FX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Vd,Y({},o,r,{ref:t}))}),jX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Wd,Y({},o,r,{ref:t}))}),zX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=zs(n);return d.createElement(Rx,Y({},o,r,{ref:t}))}),BX="AlertDialogCancel",UX=d.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=DX(BX,n),i=zs(n),s=Be(t,o);return d.createElement(Rx,Y({},i,r,{ref:s}))}),VX=AX,WX=MX,h3=OX,p3=IX,m3=zX,g3=UX,v3=FX,y3=jX,HX=VX,KX=WX,w3=d.forwardRef(({className:e,...t},n)=>v.jsx(h3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));w3.displayName=h3.displayName;const x3=d.forwardRef(({className:e,...t},n)=>v.jsxs(KX,{children:[v.jsx(w3,{}),v.jsx(p3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));x3.displayName=p3.displayName;const b3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});b3.displayName="AlertDialogHeader";const GX=d.forwardRef(({className:e,...t},n)=>v.jsx(v3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));GX.displayName=v3.displayName;const YX=d.forwardRef(({className:e,...t},n)=>v.jsx(y3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=y3.displayName;const XX=d.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce(_x(),e),...t}));XX.displayName=m3.displayName;const ZX=d.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce(_x({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));ZX.displayName=g3.displayName;const qX=pX({enableFileManager:hu(),inputDirectory:fu(),outputDirectory:fu(),enableDownloadMask:hu(),enableManualInpainting:hu(),enableUploadMask:hu(),enableAutoExtractPrompt:hu(),removeBGModel:fu(),realesrganModel:fu(),interactiveSegModel:fu()}),S3="General",F1="Model",_3="Plugins",QX=[F1,S3,_3];function JX(){const[e,t]=QT(!1),[n,r]=d.useState(F1),[o,i,s,l,u,f]=bt(F=>[F.updateAppState,F.settings,F.updateSettings,F.fileManagerState,F.setModel,F.setServerConfig]),{toast:m}=Id(),[p,g]=d.useState(i.model),[y,b]=d.useState([]),S=y.length>0;d.useEffect(()=>{g(i.model)},[i.model]);const{data:E,status:_}=ML({queryKey:["serverConfig"],queryFn:gT}),x=YY({resolver:JY(qX),defaultValues:{enableDownloadMask:i.enableDownloadMask,enableManualInpainting:i.enableManualInpainting,enableUploadMask:i.enableUploadMask,enableAutoExtractPrompt:i.enableAutoExtractPrompt,inputDirectory:l.inputDirectory,outputDirectory:l.outputDirectory,removeBGModel:E==null?void 0:E.removeBGModel,realesrganModel:E==null?void 0:E.realesrganModel,interactiveSegModel:E==null?void 0:E.interactiveSegModel}});d.useEffect(()=>{E&&(f(E),x.setValue("removeBGModel",E.removeBGModel),x.setValue("realesrganModel",E.realesrganModel),x.setValue("interactiveSegModel",E.interactiveSegModel))},[x,E]);async function C(F){s({enableDownloadMask:F.enableDownloadMask,enableManualInpainting:F.enableManualInpainting,enableUploadMask:F.enableUploadMask,enableAutoExtractPrompt:F.enableAutoExtractPrompt});const N=p.name!==i.model.name,ie=(E==null?void 0:E.removeBGModel)!==F.removeBGModel&&M,K=(E==null?void 0:E.realesrganModel)!==F.realesrganModel&&A,Z=(E==null?void 0:E.interactiveSegModel)!==F.interactiveSegModel&&D;if(N||ie||K||Z){const se=[];if(N&&se.push(`Switching model from ${i.model.name} to ${p.name}`),ie&&se.push(`Switching RemoveBG model from ${E==null?void 0:E.removeBGModel} to ${F.removeBGModel}`),K&&se.push(`Switching RealESRGAN model from ${E==null?void 0:E.realesrganModel} to ${F.realesrganModel}`),Z&&se.push(`Switching ${Ao.InteractiveSeg} model from ${E==null?void 0:E.interactiveSegModel} to ${F.interactiveSegModel}`),b(se),o({disableShortCuts:!0}),N)try{const ce=await Bj(p.name);m({title:`Switch to ${ce.name} success`}),u(p)}catch(ce){m({variant:"destructive",title:`Switch to ${p.name} failed: ${ce}`}),g(i.model)}if(ie)try{const ce=await v0(Ao.RemoveBG,F.removeBGModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RemoveBG model to ${F.removeBGModel} failed: ${ce}`})}if(K)try{const ce=await v0(Ao.RealESRGAN,F.realesrganModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch RealESRGAN model to ${F.realesrganModel} failed: ${ce}`})}if(Z)try{const ce=await v0(Ao.InteractiveSeg,F.interactiveSegModel);if(ce.status!==200)throw new Error(ce.statusText)}catch(ce){m({variant:"destructive",title:`Switch ${Ao.InteractiveSeg} model to ${F.interactiveSegModel} failed: ${ce}`})}b([]),o({disableShortCuts:!1})}}if(Zn("s",()=>{t(),e&&C(x.getValues())},[e,x,p,E]),_!=="success")return v.jsx(v.Fragment,{});const R=E.modelInfos,P=E.plugins,M=P.some(F=>F.name===Ao.RemoveBG),A=P.some(F=>F.name===Ao.RealESRGAN),D=P.some(F=>F.name===Ao.InteractiveSeg);function U(F){t(),F||C(x.getValues())}function W(F){g(F)}function q(F){return R?R.filter(N=>F.includes(N.model_type)).map(N=>v.jsxs("div",{onClick:()=>W(N),className:"px-2",children:[v.jsx("div",{className:Ce([N.name===p.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:N.name})}),v.jsx(gn,{className:"my-1"})]},N.name)):v.jsx("div",{children:"Please download model first"})}function X(){let F=fs;for(let N of R)if(p.name===N.name){F=N.model_type,F===oC&&(F=uh),F===iC&&(F=dh);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:p.name})]}),v.jsx(gn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(a5,{defaultValue:F,children:[v.jsxs(jx,{children:[v.jsx(pa,{value:fs,children:"Inpaint"}),v.jsx(pa,{value:uh,children:"Stable Diffusion"}),v.jsx(pa,{value:dh,children:"Stable Diffusion Inpaint"}),v.jsx(pa,{value:d0,children:"Other Diffusion"})]}),v.jsxs(ag,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(Su,{value:fs,children:q([fs])}),v.jsx(Su,{value:uh,children:q([uh,oC])}),v.jsx(Su,{value:dh,children:q([dh,iC])}),v.jsx(Su,{value:d0,children:q([d0])})]})]})]})]})}function ae(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"enableManualInpainting",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable manual inpainting"}),v.jsx(aa,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableDownloadMask",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable download mask"}),v.jsx(aa,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"enableAutoExtractPrompt",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Enable auto extract prompt"}),v.jsx(aa,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(sa,{children:v.jsx(co,{checked:F.value,onCheckedChange:F.onChange})})]})})]})}function V(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(al,{control:x.control,name:"removeBGModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Remove Background"}),v.jsx(aa,{children:"Remove background model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!M,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select removebg model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.removeBGModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"realesrganModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"RealESRGAN"}),v.jsx(aa,{children:"RealESRGAN Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!A,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select RealESRGAN model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.realesrganModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})}),v.jsx(gn,{}),v.jsx(al,{control:x.control,name:"interactiveSegModel",render:({field:F})=>v.jsxs(oa,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(ia,{children:"Interactive Segmentation"}),v.jsx(aa,{children:"Interactive Segmentation Model"})]}),v.jsxs(Uo,{onValueChange:F.onChange,defaultValue:F.value,disabled:!D,children:[v.jsx(sa,{children:v.jsx(go,{className:"w-auto",children:v.jsx(Vo,{placeholder:"Select interactive segmentation model"})})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:E==null?void 0:E.interactiveSegModels.map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(HX,{open:S,children:v.jsx(x3,{children:v.jsx(b3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),y?v.jsx("div",{className:"flex flex-col",children:y.map((F,N)=>v.jsx("div",{children:F},N))}):v.jsx(v.Fragment,{})]})})})}),v.jsxs(Jm,{open:e,onOpenChange:U,children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Settings",children:v.jsx(sV,{})})}),v.jsxs(Hd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:F=>F.preventDefault(),children:[v.jsx(Kd,{children:"Settings"}),v.jsx(gn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:QX.map(F=>v.jsx(wn,{variant:"ghost",onClick:()=>r(F),className:Ce(n===F?"bg-muted ":"hover:bg-muted","justify-start"),children:F},F))}),v.jsx(gn,{orientation:"vertical"}),v.jsx(wX,{...x,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:x.handleSubmit(C),children:[n===F1?X():v.jsx(v.Fragment,{}),n===S3?ae():v.jsx(v.Fragment,{}),n===_3?V():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(wn,{onClick:()=>U(!1),children:"Ok"})})]})})})]})]})]})]})}const eZ="/assets/kofi_button_black-XI_Dr2zg.png";function tZ(){return v.jsxs(Jm,{children:[v.jsx(kx,{asChild:!0,children:v.jsx(yn,{tooltip:"Buy me a coffee",children:v.jsx(XU,{})})}),v.jsxs(Hd,{children:[v.jsx(Kd,{children:"Buy me a coffee"}),v.jsx(vP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:eZ,className:"h-[32px]"})})})]})]})}const nZ=()=>{const[e,t,n,r,o,i,s,l,u,f,m,p,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:b}=Id(),[S,E]=Px(t),[_,x]=d.useState(!1),C=()=>{f()},R=()=>{m()},P=()=>{p()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(PY,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const D=await Vj(M,A);l(D)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(f1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(tV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(f1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await gF(M)}catch(D){b({variant:"destructive",description:D.message?D.message:D.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){b({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||f()},children:v.jsx(qT,{})}),t?v.jsxs(KW,{open:_,children:[v.jsx(GW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(yn,{tooltip:"Run custom mask",children:v.jsx(uz,{})})}),v.jsx(MP,{children:E?v.jsx("img",{src:S.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(yn,{disabled:n,tooltip:"Rerun previous mask",onClick:C,onMouseEnter:R,onMouseLeave:P,children:v.jsx(iV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(yH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(tZ,{}),v.jsx(MW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(JX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},rZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},oZ=function(e){return-Math.cos(e*Math.PI)/2+.5},iZ=function(e){return e},sZ=function(e){return e*e},aZ=function(e){return e*(2-e)},lZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},cZ=function(e){return e*e*e},uZ=function(e){return--e*e*e+1},dZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},fZ=function(e){return e*e*e*e},hZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},mZ=function(e){return e*e*e*e*e},gZ=function(e){return 1+--e*e*e*e*e},vZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},E3={easeOut:oZ,linear:iZ,easeInQuad:sZ,easeOutQuad:aZ,easeInOutQuad:lZ,easeInCubic:cZ,easeOutCubic:uZ,easeInOutCubic:dZ,easeInQuart:fZ,easeOutQuart:hZ,easeInOutQuart:pZ,easeInQuint:mZ,easeOutQuint:gZ,easeInOutQuint:vZ},C3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},jo=function(e){e.mounted&&(C3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function $3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;jo(e),e.animation=function(){if(!e.mounted)return C3(e.animation);var s=new Date().getTime()-o,l=s/n,u=E3[t],f=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(f),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function yZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Bs(e,t,n,r){var o=yZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=t.scale-l,p=t.positionX-u,g=t.positionY-f;n===0?i(t.scale,t.positionX,t.positionY):$3(e,r,n,function(y){var b=l+m*y,S=u+p*y,E=f+g*y;i(b,S,E)})}}function wZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,f=r-l,m=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:f,newContentHeight:u,newDiffHeight:m}}var xZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,f=e-t-l,m=l,p=r-o-u,g=u;return{minPositionX:f,maxPositionX:m,minPositionY:p,maxPositionY:g}},qx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=wZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,f=i.newDiffWidth,m=i.newContentHeight,p=i.newDiffHeight,g=xZ(s,u,f,l,m,p,!!o);return g},j1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},vc=function(e,t){var n=qx(e,t);return e.bounds=n,n};function dg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,f=n.maxPositionX,m=n.maxPositionY,p=0,g=0;s&&(p=o,g=i);var y=j1(e,l-p,f+p,r),b=j1(t,u-g,m+g,r);return{x:y,y:b}}function fg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,f=s.positionY,m=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:f};var p=u-t*m,g=f-n*m,y=dg(p,g,o,i,0,0,null);return y}function Zd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var N2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=hg(i,n);return!u},D2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},bZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},SZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,f=e.wrapperComponent;if(!(s||!f||!e.bounds)){var m=e.bounds,p=m.maxPositionX,g=m.minPositionX,y=m.maxPositionY,b=m.minPositionY,S=n>p||ny||rp?f.offsetWidth:e.setup.minPositionX||0,x=r>y?f.offsetHeight:e.setup.minPositionY||0,C=fg(e,_,x,o,e.bounds,l||u),R=C.x,P=C.y;return{scale:o,positionX:S?R:n,positionY:E?P:r}}}function EZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,f=u.scale,m=u.positionX,p=u.positionY;if(!(s===null||l===null||t===m&&n===p)){var g=dg(t,n,l,i,r,o,s),y=g.x,b=g.y;e.setTransformState(f,y,b)}}var CZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,f=o.positionY;if(!r)return{x:u,y:f};var m=t-r.x,p=n-r.y,g=s?u:m,y=l?f:p;return{x:g,y}},sm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},$Z=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},RZ=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,f=!u||l>1||!i||t;return!(!f||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function I2(e,t,n,r,o,i,s,l,u,f){if(o){if(t>s&&n>s){var m=s+(e-s)*f;return m>u?u:mi?i:m}}return r?t:j1(e,i,s,o)}function TZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function PZ(e,t){var n=$Z(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var f=TZ(s,l),m=t.x-r.x,p=t.y-r.y,g=m/f,y=p/f,b=u-o,S=m*m+p*p,E=Math.sqrt(S)/b;e.velocity={velocityX:g,velocityY:y,total:E}}e.lastMousePosition=t,e.velocityTime=u}}function AZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=RZ(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,f=n.maxPositionX,m=n.minPositionX,p=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,b=r.alignmentAnimation,S=r.zoomAnimation,E=r.panning,_=E.lockAxisY,x=E.lockAxisX,C=S.animationType,R=b.sizeX,P=b.sizeY,M=b.velocityAlignmentTime,A=M,D=kZ(e,u),U=Math.max(D,A),W=sm(e,R),q=sm(e,P),X=W*o.offsetWidth/100,ae=q*o.offsetHeight/100,V=f+X,F=m-X,N=p+ae,ie=g-ae,K=e.transformState,Z=new Date().getTime();$3(e,C,U,function(H){var se=e.transformState,ce=se.scale,Ve=se.positionX,Ue=se.positionY,We=new Date().getTime()-Z,Oe=We/A,he=E3[b.animationType],xe=1-he(Math.min(1,Oe)),$e=1-H,Ae=Ve+s*$e,Me=Ue+l*$e,je=I2(Ae,K.positionX,Ve,x,y,m,f,F,V,xe),Mt=I2(Me,K.positionY,Ue,_,y,g,p,ie,N,xe);(Ve!==Ae||Ue!==Me)&&e.setTransformState(ce,je,Mt)})}}function L2(e,t){var n=e.transformState.scale;jo(e),vc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?SZ(e,t):bZ(e,t)}function R3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,f=o.animationType,m=i||t.1&&p;g?AZ(e):R3(e)}}function Qx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Zd(Wr(t,2),i,s,0,!1),f=vc(e,u),m=fg(e,n,r,u,f,l),p=m.x,g=m.y;return{scale:u,positionX:p,positionY:g}}function k3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,f=u.disabled,m=u.animationTime,p=u.animationType,g=f||r>=s;if((r>=1||l)&&R3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,b=n||o.offsetHeight/2,S=Qx(e,s,y,b);S&&Bs(e,S,m,p)}}var $s=function(){return $s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},XZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=hg(s,o);return!u},ZZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},qZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},D3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},QZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,f=l.size,m=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var p=t/r,g=p*n;return Zd(Wr(g,2),s,i,f,!m&&!u)},JZ=160,eq=100,tq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(jo(e),Nt(_t(e),t,r),Nt(_t(e),t,o))},nq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,f=s.limitToBounds,m=s.centerZoomedOut,p=s.zoomAnimation,g=s.wheel,y=s.disablePadding,b=s.smooth,S=p.size,E=p.disabled,_=g.step,x=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var C=KZ(t,null),R=b?x*Math.abs(t.deltaY):_,P=GZ(e,C,R,!t.ctrlKey);if(u!==P){var M=vc(e,P),A=N3(t,i,u),D=E||S===0||m||y,U=f&&D,W=fg(e,A.x,A.y,P,M,U),q=W.x,X=W.y;e.previousWheelEvent=t,e.setTransformState(P,q,X),Nt(_t(e),t,r),Nt(_t(e),t,o)}},rq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;B1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(k3(e,t.x,t.y),e.wheelAnimationTimer=null)},eq);var i=YZ(e,t);i&&(B1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(_t(e),t,r),Nt(_t(e),t,o))},JZ))},oq=function(e,t){var n=D3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,jo(e)},iq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,f=u.disabled,m=u.size;if(!(r===null||!n)){var p=qZ(t,o,n);if(!(!Number.isFinite(p.x)||!Number.isFinite(p.y))){var g=D3(t),y=QZ(e,g);if(y!==o){var b=vc(e,y),S=f||m===0||l,E=s&&S,_=fg(e,p.x,p.y,y,b,E),x=_.x,C=_.y;e.pinchMidpoint=p,e.lastDistance=g,e.setTransformState(y,x,C)}}}},sq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,k3(e,t==null?void 0:t.x,t==null?void 0:t.y)},I3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;B1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(_t(e),t,n)},r)},aq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(_t(e),t,r),M3(e,s,l,function(){return Nt(_t(e),t,o)}),I3(e,t)};function lq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,f=l.onZoom,m=n.doubleClick,p=m.disabled,g=m.mode,y=m.step,b=m.animationTime,S=m.animationType;if(!p&&!r){if(g==="reset")return aq(e,t);if(!i)return console.error("No ContentComponent found");var E=g==="zoomOut"?-1:1,_=P3(e,E,y);if(s!==_){Nt(_t(e),t,u);var x=N3(t,i,s),C=Qx(e,_,x.x,x.y);if(!C)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(_t(e),t,f),Bs(e,C,b,S),I3(e,t)}}}var cq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,f=o==null?void 0:o.contains(u),m=n&&u&&f&&!s;if(!m)return!1;var p=hg(u,l);return!p},uq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){vc(n,n.transformState.scale),n.setup=z2(r)},this.initializeWindowEvents=function(){var r,o=j0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=j0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),jo(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=j0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(_t(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(_t(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=WZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(tq(n,r),nq(n,r),rq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),jo(n),L2(n,r),Nt(_t(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=D2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),F2(n,r.clientX,r.clientY),Nt(_t(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(MZ(n),Nt(_t(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=XZ(n,r);u&&(oq(n,r),jo(n),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=ZZ(n);u&&(r.preventDefault(),r.stopPropagation(),iq(n,r),Nt(_t(n),r,s),Nt(_t(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(sq(n),Nt(_t(n),r,i),Nt(_t(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=N2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,jo(n);var u=r.touches,f=u.length===1,m=u.length===2;f&&(jo(n),L2(n,r),Nt(_t(n),r,i)),m&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=D2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];F2(n,l.clientX,l.clientY),Nt(_t(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=cq(n,r);i&&lq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=_t(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=O3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):UZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return _t(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,vc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=_t(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=z2(this.props),this.transformState=T3(this.props)}return e}(),Jx=Fe.createContext(null),dq=function(e,t){return typeof e=="function"?e(t):e},fq=Fe.forwardRef(function(e,t){var n=d.useRef(new uq(e)).current,r=dq(e.children,z1(n));return d.useImperativeHandle(t,function(){return z1(n)},[n]),d.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(Jx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=d.useRef(null),r=d.useContext(Jx);return d.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",$s({},e,{ref:VZ([n,t])}))});function hq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,B2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};hq(pq);var mq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,f=u===void 0?{}:u,m=e.contentProps,p=m===void 0?{}:m,g=d.useContext(Jx),y=g.init,b=g.cleanupWindowEvents,S=d.useRef(null),E=d.useRef(null);return d.useEffect(function(){var _=S.current,x=E.current;return _!==null&&x!==null&&y&&(y==null||y(_,x)),function(){b==null||b()}},[]),Fe.createElement("div",$s({},f,{ref:S,className:"react-transform-wrapper ".concat(B2.wrapper," ").concat(r),style:s}),Fe.createElement("div",$s({},p,{ref:E,className:"react-transform-component ".concat(B2.content," ").concat(i),style:l}),t))};const L3=["PageUp","PageDown"],F3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],j3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},qd="Slider",[U1,gq,vq]=Gd(qd),[z3,Cte]=Mn(qd,[vq]),[yq,pg]=z3(qd),wq=d.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:f=[r],value:m,onValueChange:p=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...b}=e,[S,E]=d.useState(null),_=Be(t,V=>E(V)),x=d.useRef(new Set),C=d.useRef(0),R=s==="horizontal",P=S?!!S.closest("form"):!0,M=R?xq:bq,[A=[],D]=Zr({prop:m,defaultProp:f,onChange:V=>{var F;(F=[...x.current][C.current])===null||F===void 0||F.focus(),p(V)}}),U=d.useRef(A);function W(V){const F=Pq(A,V);ae(V,F)}function q(V){ae(V,C.current)}function X(){const V=U.current[C.current];A[C.current]!==V&&g(A)}function ae(V,F,{commit:N}={commit:!1}){const ie=Nq(i),K=Dq(Math.round((V-r)/i)*i+r,ie),Z=fd(K,[r,o]);D((H=[])=>{const se=kq(H,Z,F);if(Oq(se,u*i)){C.current=se.indexOf(Z);const ce=String(se)!==String(H);return ce&&N&&g(se),ce?se:H}else return H})}return d.createElement(yq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:C,thumbs:x.current,values:A,orientation:s},d.createElement(U1.Provider,{scope:e.__scopeSlider},d.createElement(U1.Slot,{scope:e.__scopeSlider},d.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},b,{ref:_,onPointerDown:de(b.onPointerDown,()=>{l||(U.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:W,onSlideMove:l?void 0:q,onSlideEnd:l?void 0:X,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:V,direction:F})=>{if(!l){const K=L3.includes(V.key)||V.shiftKey&&F3.includes(V.key)?10:1,Z=C.current,H=A[Z],se=i*K*F;ae(H+se,Z,{commit:!0})}}})))),P&&A.map((V,F)=>d.createElement(Rq,{key:F,name:n?n+(A.length>1?"[]":""):void 0,value:V})))}),[B3,U3]=z3(qd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),xq=d.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:f,...m}=e,[p,g]=d.useState(null),y=Be(t,C=>g(C)),b=d.useRef(),S=Tc(o),E=S==="ltr",_=E&&!i||!E&&i;function x(C){const R=b.current||p.getBoundingClientRect(),P=[0,R.width],A=eb(P,_?[n,r]:[r,n]);return b.current=R,A(C-R.left)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width"},d.createElement(V3,Y({dir:S,"data-orientation":"horizontal"},m,{ref:y,style:{...m.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const R=x(C.clientX);s==null||s(R)},onSlideMove:C=>{const R=x(C.clientX);l==null||l(R)},onSlideEnd:()=>{b.current=void 0,u==null||u()},onStepKeyDown:C=>{const P=j3[_?"from-left":"from-right"].includes(C.key);f==null||f({event:C,direction:P?-1:1})}})))}),bq=d.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...f}=e,m=d.useRef(null),p=Be(t,m),g=d.useRef(),y=!o;function b(S){const E=g.current||m.current.getBoundingClientRect(),_=[0,E.height],C=eb(_,y?[r,n]:[n,r]);return g.current=E,C(S-E.top)}return d.createElement(B3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},d.createElement(V3,Y({"data-orientation":"vertical"},f,{ref:p,style:{...f.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:S=>{const E=b(S.clientY);i==null||i(E)},onSlideMove:S=>{const E=b(S.clientY);s==null||s(E)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:S=>{const _=j3[y?"from-bottom":"from-top"].includes(S.key);u==null||u({event:S,direction:_?-1:1})}})))}),V3=d.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...f}=e,m=pg(qd,n);return d.createElement(Pe.span,Y({},f,{ref:t,onKeyDown:de(e.onKeyDown,p=>{p.key==="Home"?(s(p),p.preventDefault()):p.key==="End"?(l(p),p.preventDefault()):L3.concat(F3).includes(p.key)&&(u(p),p.preventDefault())}),onPointerDown:de(e.onPointerDown,p=>{const g=p.target;g.setPointerCapture(p.pointerId),p.preventDefault(),m.thumbs.has(g)?g.focus():r(p)}),onPointerMove:de(e.onPointerMove,p=>{p.target.hasPointerCapture(p.pointerId)&&o(p)}),onPointerUp:de(e.onPointerUp,p=>{const g=p.target;g.hasPointerCapture(p.pointerId)&&(g.releasePointerCapture(p.pointerId),i(p))})}))}),Sq="SliderTrack",_q=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(Sq,n);return d.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),U2="SliderRange",Eq=d.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=pg(U2,n),i=U3(U2,n),s=d.useRef(null),l=Be(t,s),u=o.values.length,f=o.values.map(g=>W3(g,o.min,o.max)),m=u>1?Math.min(...f):0,p=100-Math.max(...f);return d.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:m+"%",[i.endEdge]:p+"%"}}))}),V2="SliderThumb",Cq=d.forwardRef((e,t)=>{const n=gq(e.__scopeSlider),[r,o]=d.useState(null),i=Be(t,l=>o(l)),s=d.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return d.createElement($q,Y({},e,{ref:i,index:s}))}),$q=d.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=pg(V2,n),s=U3(V2,n),[l,u]=d.useState(null),f=Be(t,E=>u(E)),m=yx(l),p=i.values[r],g=p===void 0?0:W3(p,i.min,i.max),y=Tq(r,i.values.length),b=m==null?void 0:m[s.size],S=b?Aq(b,g,s.direction):0;return d.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),d.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${S}px)`}},d.createElement(U1.ItemSlot,{scope:e.__scopeSlider},d.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":p,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:f,style:p===void 0?{display:"none"}:e.style,onFocus:de(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),Rq=e=>{const{value:t,...n}=e,r=d.useRef(null),o=zx(t);return d.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const f=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(f)}},[o,t]),d.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function W3(e,t,n){const i=100/(n-t)*(e-t);return fd(i,[0,100])}function Tq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Pq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Aq(e,t,n){const r=e/2,i=eb([0,50],[0,r]);return(r-i(t)*n)*n}function Mq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Mq(e);return Math.min(...n)>=t}return!0}function eb(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Nq(e){return(String(e).split(".")[1]||"").length}function Dq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const H3=wq,Iq=_q,Lq=Eq,Fq=Cq,uo=d.forwardRef(({className:e,...t},n)=>v.jsxs(H3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Iq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Lq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Fq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=H3.displayName;const ll={capture:!0,passive:!1},jq=2,W2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},zq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,f,m,{x:p,y:g,width:y,height:b},S,E,_,x,C,R]=bt(H=>[H.imageWidth,H.imageHeight,H.isInpainting,H.isSD(),H.cropperState,H.setCropperX,H.setCropperY,H.setCropperWidth,H.setCropperHeight,H.isCropperExtenderResizing,H.setIsCropperExtenderResizing]),[P,M]=d.useState(!1);d.useEffect(()=>{S(Math.round((o-512)/2)),E(Math.round((r-512)/2))},[r,o,l,u]);const[A,D]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),U=()=>{},W=(H,se)=>W2(H,se,p,y,n,o),q=(H,se)=>W2(H,se,g,b,t,r),X=H=>{if(f)return;const se=H.clientX,ce=H.clientY,Ve=Math.round((ce-A.startResizeY)/i),Ue=Math.round((se-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Me,je]=q(Ae,$e);x(je),E(Me)},Oe=()=>{const $e=A.initHeight+Ve,[Ae,Me]=q(A.initY,$e);x(Me),E(Ae)},he=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Me,je]=W(Ae,$e);_(je),S(Me)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Me]=W(A.initX,$e);_(Me),S(Ae)};if(C)switch(A.ord){case"topleft":{We(),he();break}case"topright":{We(),xe();break}case"bottomleft":{Oe(),he();break}case"bottomright":{Oe(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Oe();break}case"left":{he();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Me,je]=W($e,A.initWidth),[Mt,ct]=q(Ae,A.initHeight);_(je),x(ct),S(Me),E(Mt)}},ae=()=>{C&&R(!1),P&&M(!1)};d.useEffect(()=>{if(C||P)return document.addEventListener("pointermove",X,ll),document.addEventListener("pointerup",ae,ll),document.addEventListener("pointercancel",ae,ll),()=>{document.removeEventListener("pointermove",X,ll),document.removeEventListener("pointerup",ae,ll),document.removeEventListener("pointercancel",ae,ll)}},[C,P,y,b,A]);const V=H=>{const{ord:se}=H.target.dataset;se&&(R(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:se}))},F=(H,se,ce)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Oe="0",he="0",xe=ce,$e="-6px";return ce===""&&($e="50%",se==="left"||se==="right"?(xe="top",he="-50%"):(xe="left",Oe="-50%")),v.jsx("div",{className:Ce(We,H),style:{[se]:-6,[xe]:$e,transform:`translate(${Oe}, ${he}) scale(${1/i})`},"data-ord":se+ce,"aria-label":se+ce,tabIndex:-1,role:"button"})},N=()=>v.jsxs("div",{onFocus:U,onPointerDown:V,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),F("cursor-nw-resize","top","left"),F("cursor-ne-resize","top","right"),F("cursor-sw-resize","bottom","left"),F("cursor-se-resize","bottom","right"),F("cursor-ns-resize","top",""),F("cursor-ns-resize","bottom",""),F("cursor-ew-resize","left",""),F("cursor-ew-resize","right","")]}),ie=H=>{M(!0),D({initX:p,initY:g,initHeight:b,initWidth:y,startResizeX:H.clientX,startResizeY:H.clientY,ord:""})},K=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",b]}),Z=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:b,width:y,outlineWidth:`${jq/i*1.3}px`}});return s===!1||!m?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:b,width:y,left:p,top:g},children:[Z(),K(),N()]})})},Bq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(wn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(wn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Uq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Vq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Uq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Wq=()=>v.jsx("div",{children:v.jsx(Bq,{})}),cl={capture:!0,passive:!1},Hq=2,H2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:f,y:m,width:p,height:g},y,b,S,E,_,x,C]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[R,P]=d.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>H2(ie,K,f,n),D=(ie,K)=>H2(ie,K,m,t),U=ie=>{if(i)return;const K=ie.clientX,Z=ie.clientY,H=Math.round((Z-R.startResizeY)/r),se=Math.round((K-R.startResizeX)/r),ce=()=>{const Oe=R.initHeight-H,he=R.initY+H;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initHeight-Math.abs(R.initY));else{const Ae=D(he,Oe);xe=Ae[0],$e=Ae[1]}E($e),b(xe)},Ve=()=>{const Oe=R.initHeight+H;let[he,xe]=D(R.initY,Oe);_===Ln.xy&&xe{const Oe=R.initWidth-se,he=R.initX+se;let xe=he,$e=Oe;if(_===Ln.xy)xe>0&&(xe=0,$e=R.initWidth-Math.abs(R.initX));else{const Ae=A(he,Oe);xe=Ae[0],$e=Ae[1]}S($e),y(xe)},We=()=>{const Oe=R.initWidth+se;let[he,xe]=A(R.initX,Oe);_===Ln.xy&&xe{x&&C(!1)};d.useEffect(()=>{if(x)return document.addEventListener("pointermove",U,cl),document.addEventListener("pointerup",W,cl),document.addEventListener("pointercancel",W,cl),()=>{document.removeEventListener("pointermove",U,cl),document.removeEventListener("pointerup",W,cl),document.removeEventListener("pointercancel",W,cl)}},[x,p,g,R]);const q=ie=>{const{ord:K}=ie.target.dataset;K&&(C(!0),P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},X=(ie,K,Z)=>{const ce="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Z,Oe="-6px";return Z===""&&(Oe="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ce,ie),style:{[K]:-6,[We]:Oe,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Z,"aria-label":K+Z,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:q,className:"absolute top-0 h-full w-full",children:[[Ln.y,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),X("cursor-ns-resize","top",""),X("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[Ln.x,Ln.xy].includes(_)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),X("cursor-ew-resize","left",""),X("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),_===Ln.xy?v.jsxs(v.Fragment,{children:[X("cursor-nw-resize","top","left"),X("cursor-ne-resize","top","right"),X("cursor-sw-resize","bottom","left"),X("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),V=ie=>{P({initX:f,initY:m,initHeight:g,initWidth:p,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},F=()=>v.jsxs("div",{className:tx("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:V,children:[p," x ",g]}),N=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:p,outlineWidth:`${Hq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:p,left:f,top:m},children:[N(),F(),ae()]})})},Gq=200,Yq=10,Xq=200,mu=300;function Zq(e){const{file:t}=e,{toast:n}=Id(),[r,o,i,s,l,u,f,m,p,g,y,b,S,E,_,x,C,R,P,M,A,D]=bt(G=>[G.disableShortCuts,G.windowSize,G.isInpainting,G.imageWidth,G.imageHeight,G.settings,G.serverConfig.enableAutoSaving,G.setImageSize,G.setBaseBrushSize,G.interactiveSegState,G.updateInteractiveSegState,G.handleCanvasMouseDown,G.handleCanvasMouseMove,G.undo,G.redo,G.undoDisabled(),G.redoDisabled(),G.getIsProcessing(),G.updateAppState,G.runMannually(),G.runInpainting,G.isCropperExtenderResizing]),U=bt(G=>G.editorState.baseBrushSize),W=bt(G=>G.getBrushSize()),q=bt(G=>G.editorState.renders),X=bt(G=>G.editorState.extraMasks),ae=bt(G=>G.editorState.temporaryMasks),V=bt(G=>G.editorState.lineGroups),F=bt(G=>G.editorState.curLineGroup),[N,ie]=d.useState(!1),[K,Z]=Px(t),[H,se]=d.useState(),[ce,Ve]=d.useState(),[{x:Ue,y:We},Oe]=d.useState({x:-1,y:-1}),[he,xe]=d.useState(!1),[$e,Ae]=d.useState(!1),[Me,je]=d.useState(!1),[Mt,ct]=d.useState(1),[Kt,Er]=d.useState(!1),[gt,Vs]=d.useState(1),L=o.width/2,Q=o.height/2,J=d.useRef(null),[we,me]=d.useState(!1),[fe,Re]=d.useState(!1),[ft,ht]=d.useState(0),_n=d.useCallback(()=>F.length!==0,[F]);d.useEffect(()=>{if(!ce||!Z||s===0||l===0)return;const G=q.length===0?K:q[q.length-1];ce.canvas.width=s,ce.canvas.height=l,ce.clearRect(0,0,ce.canvas.width,ce.canvas.height),ce.drawImage(G,0,0,s,l)},[q,K,Z,ce,l,s]),d.useEffect(()=>{!H||!Z||s===0||l===0||(H.canvas.width=s,H.canvas.height=l,H.clearRect(0,0,H.canvas.width,H.canvas.height),ae.forEach(G=>{H.drawImage(G,0,0,s,l)}),X.forEach(G=>{H.drawImage(G,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&H.drawImage(g.tmpInteractiveSegMask,0,0,s,l),Yk(H,F))},[ae,X,Z,g,H,F,l,s]);const Cr=d.useCallback(async()=>{let G=t;if(q.length>0){const Ye=q[q.length-1];G=await Nu(Ye.currentSrc,t.name,t.type)}return G},[t,q]),Ni=()=>q.length!==0,Co=d.useCallback(()=>{let G=512,Ye=512;return Z?(q.length===0?(G=K.naturalWidth,Ye=K.naturalHeight):q.length!==0&&(G=q[q.length-1].width,Ye=q[q.length-1].height),[G,Ye]):[G,Ye]},[K,Z,q]);d.useEffect(()=>{var tf;if(!Z)return;const[G,Ye]=Co();(G!==s||Ye!==l)&&m(G,Ye);const st=o.width/G,Qr=(o.height-Gq)/Ye;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),Vs(an),ct(an),console.log(`[on file load] image size: ${G}x${Ye}, scale: ${an}, initialCentered: ${we}`),H!=null&&H.canvas&&(console.log("[on file load] set canvas size"),G!=H.canvas.width&&(H.canvas.width=G),Ye!=H.canvas.height&&(H.canvas.height=Ye)),we||((tf=J.current)==null||tf.centerView(an,1),console.log("[on file load] centerView"),me(!0))},[J,l,s,K,Z,o,we,Co]),d.useEffect(()=>{var G;console.log("[useEffect] centerView"),(G=J==null?void 0:J.current)==null||G.centerView(gt,1)},[l,s,J,gt]);const Vn=d.useCallback(()=>{if(!gt||!o)return;const G=J.current;if(!G)return;const Ye=(o.width-s*gt)/2,st=(o.height-l*gt)/2;G.setTransform(Ye,st,gt,200,"easeOutQuad"),G.instance.transformState.scale&&(G.instance.transformState.scale=gt),ct(gt),Er(!1)},[J,o,l,s,o.height,gt]);d.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{R||(fe?Re(!1):Vn())},[fe,i,Vn]);const Di=G=>{const Ye=G.nativeEvent;Oe({x:Ye.pageX,y:Ye.pageY})},Ws=G=>{R||g.isInteractiveSeg||Me||fe&&F.length!==0&&S(f0(G))},Ii=async G=>{P({isPluginRunning:!0});const Ye=await Cr();try{const st=await vT(!0,Ao.InteractiveSeg,Ye,void 0,G),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},Mc=G=>{if(dC(G)){je(!1);return}!_n()||g.isInteractiveSeg||Me||!K.src||!(H!=null&&H.canvas)||i||fe&&(M?Re(!1):A())},bg=G=>{if(g.isInteractiveSeg){const Ye=f0(G),st=[...g.clicks];uC(G)?st.push([Ye.x,Ye.y,0,st.length]):st.push([Ye.x,Ye.y,1,st.length]),Ii(st),y({clicks:st})}},Sg=G=>{if(!(R||g.isInteractiveSeg||Me||!Z||!(H!=null&&H.canvas))&&!uC(G)){if(dC(G)){je(!0);return}Re(!0),b(f0(G))}},Jd=G=>{G.preventDefault(),E()};Zn("meta+z,ctrl+z",Jd);const Oc=G=>{G.preventDefault(),_()};Zn("shift+ctrl+z,shift+meta+z",Oc),s2("Tab",G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},G=>{G==null||G.preventDefault(),G==null||G.stopPropagation(),Ni()&&(window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu))});const Nc=d.useCallback(async()=>{if(t===void 0)return;if(f&&q.length>0){try{await Hj(q[q.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const G=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ye=q[q.length-1];if(bF(Ye.currentSrc,G),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Wh(s,l,V),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,f,q,u,l,s,V]);Zn("meta+s,ctrl+s",Nc);const Dc=G=>{G!==he&&!Me&&!D&&xe(G)},_g=d.useCallback(()=>{if(R)return"default";if(Me)return"grab";if(he)return"none"},[he,Me,R]);Zn("[",()=>{let G=U;U>10&&(G=U-10),U<=10&&U>0&&(G=U-5),p(G)},[U]),Zn("]",()=>{p(U+10)},[U]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await vF()&&q.length>0&&H!=null&&H.canvas&&(await xF(H==null?void 0:H.canvas),n({title:"Copy inpainting result to clipboard"}))},[q,H]),s2(" ",G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!1),je(!0))},G=>{r||(G==null||G.preventDefault(),G==null||G.stopPropagation(),xe(!0),je(!1))});const Ic=()=>{var Ye,st,Qr,an;let G=gt;return((st=(Ye=J.current)==null?void 0:Ye.instance)==null?void 0:st.transformState.scale)!==void 0&&(G=(an=(Qr=J.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),G},ef=(G,Ye)=>{const st=Ic();return{width:`${W*st}px`,height:`${W*st}px`,left:`${G}px`,top:`${Ye}px`,transform:"translate(-50%, -50%)"}},Lc=G=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:G}),Eg=G=>{p(G),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},Cg=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(dK,{})}),$g=()=>v.jsx(fq,{ref:G=>{G&&(J.current=G)},panning:{disabled:!Me,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:G=>{ct(G.state.scale)},children:v.jsxs(mq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},ref:G=>{if(G&&!ce){const Ye=G.getContext("2d");Ye&&Ve(Ye)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",R?"pointer-events-none animate-pulse duration-600":""),style:{cursor:_g(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${mu}ms`},onContextMenu:G=>{G.preventDefault()},onMouseOver:()=>{Dc(!0),Ae(!1)},onFocus:()=>Dc(!0),onMouseLeave:()=>Dc(!1),onMouseDown:Sg,onMouseUp:bg,onMouseMove:Ws,ref:G=>{if(G&&!H){const Ye=G.getContext("2d");Ye&&se(Ye)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:N&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${mu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(zq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showCropper}),v.jsx(Kq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Ic(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Vq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Di,onMouseUp:Mc,children:[$g(),he&&!i&&!Me&&(g.isInteractiveSeg?Cg():Lc(ef(Ue,We))),$e&&Lc(ef(L,Q)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Xq,step:1,tabIndex:-1,value:[U],onValueChange:G=>Eg(G[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(yn,{tooltip:"Reset zoom & pan",disabled:Mt===gt&&Kt===!1,onClick:Vn,children:v.jsx(QU,{})}),v.jsx(yn,{tooltip:"Undo",onClick:Jd,disabled:x,children:v.jsx(aV,{})}),v.jsx(yn,{tooltip:"Redo",onClick:Oc,disabled:C,children:v.jsx(oV,{})}),v.jsx(yn,{tooltip:"Show original image",onPointerDown:G=>{G.preventDefault(),ie(()=>(window.setTimeout(()=>{ht(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{ht(0)},10),window.setTimeout(()=>{ie(!1)},mu)},disabled:q.length===0,children:v.jsx(JU,{})}),v.jsx(yn,{tooltip:"Save Image",disabled:!q.length,onClick:Nc,children:v.jsx(ZU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(yn,{tooltip:"Run Inpainting",disabled:R||!_n()&&X.length===0,onClick:()=>{A()},children:v.jsx(qU,{})}):v.jsx(v.Fragment,{})]})]})]})}const qq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},V1=["Enter"," "],Qq=["ArrowDown","PageUp","Home"],K3=["ArrowUp","PageDown","End"],Jq=[...Qq,...K3],eQ={ltr:[...V1,"ArrowRight"],rtl:[...V1,"ArrowLeft"]},tQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},mg="Menu",[md,nQ,rQ]=Gd(mg),[za,G3]=Mn(mg,[rQ,Fs,tg]),gg=Fs(),Y3=tg(),[X3,Us]=za(mg),[oQ,Qd]=za(mg),iQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=gg(t),[u,f]=d.useState(null),m=d.useRef(!1),p=Ft(i),g=Tc(o);return d.useEffect(()=>{const y=()=>{m.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>m.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),d.createElement(jd,l,d.createElement(X3,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:f},d.createElement(oQ,{scope:t,onClose:d.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:m,dir:g,modal:s},r)))},Z3=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=gg(n);return d.createElement(Vm,Y({},o,r,{ref:t}))}),q3="MenuPortal",[sQ,Q3]=za(q3,{forceMount:void 0}),aQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Us(q3,t);return d.createElement(sQ,{scope:t,forceMount:n},d.createElement(Sn,{present:n||i.open},d.createElement(zd,{asChild:!0,container:o},r)))},bo="MenuContent",[lQ,tb]=za(bo),cQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},s.modal?d.createElement(uQ,Y({},o,{ref:t})):d.createElement(dQ,Y({},o,{ref:t})))))}),uQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu),r=d.useRef(null),o=Be(t,r);return d.useEffect(()=>{const i=r.current;if(i)return Qm(i)},[]),d.createElement(nb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:de(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),dQ=d.forwardRef((e,t)=>{const n=Us(bo,e.__scopeMenu);return d.createElement(nb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),nb=d.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y,disableOutsideScroll:b,...S}=e,E=Us(bo,n),_=Qd(bo,n),x=gg(n),C=Y3(n),R=nQ(n),[P,M]=d.useState(null),A=d.useRef(null),D=Be(t,A,E.onContentChange),U=d.useRef(0),W=d.useRef(""),q=d.useRef(0),X=d.useRef(null),ae=d.useRef("right"),V=d.useRef(0),F=b?qm:d.Fragment,N=b?{as:Zo,allowPinchZoom:!0}:void 0,ie=Z=>{var H,se;const ce=W.current+Z,Ve=R().filter($e=>!$e.disabled),Ue=document.activeElement,We=(H=Ve.find($e=>$e.ref.current===Ue))===null||H===void 0?void 0:H.textValue,Oe=Ve.map($e=>$e.textValue),he=kQ(Oe,ce,We),xe=(se=Ve.find($e=>$e.textValue===he))===null||se===void 0?void 0:se.ref.current;(function $e(Ae){W.current=Ae,window.clearTimeout(U.current),Ae!==""&&(U.current=window.setTimeout(()=>$e(""),1e3))})(ce),xe&&setTimeout(()=>xe.focus())};d.useEffect(()=>()=>window.clearTimeout(U.current),[]),Xm();const K=d.useCallback(Z=>{var H,se;return ae.current===((H=X.current)===null||H===void 0?void 0:H.side)&&PQ(Z,(se=X.current)===null||se===void 0?void 0:se.area)},[]);return d.createElement(lQ,{scope:n,searchRef:W,onItemEnter:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),onItemLeave:d.useCallback(Z=>{var H;K(Z)||((H=A.current)===null||H===void 0||H.focus(),M(null))},[K]),onTriggerLeave:d.useCallback(Z=>{K(Z)&&Z.preventDefault()},[K]),pointerGraceTimerRef:q,onPointerGraceIntentChange:d.useCallback(Z=>{X.current=Z},[])},d.createElement(F,N,d.createElement(Ym,{asChild:!0,trapped:o,onMountAutoFocus:de(i,Z=>{var H;Z.preventDefault(),(H=A.current)===null||H===void 0||H.focus()}),onUnmountAutoFocus:s},d.createElement(Ec,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:f,onPointerDownOutside:m,onFocusOutside:p,onInteractOutside:g,onDismiss:y},d.createElement(QP,Y({asChild:!0},C,{dir:_.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:de(u,Z=>{_.isUsingKeyboardRef.current||Z.preventDefault()})}),d.createElement(Wm,Y({role:"menu","aria-orientation":"vertical","data-state":oA(E.open),"data-radix-menu-content":"",dir:_.dir},x,S,{ref:D,style:{outline:"none",...S.style},onKeyDown:de(S.onKeyDown,Z=>{const se=Z.target.closest("[data-radix-menu-content]")===Z.currentTarget,ce=Z.ctrlKey||Z.altKey||Z.metaKey,Ve=Z.key.length===1;se&&(Z.key==="Tab"&&Z.preventDefault(),!ce&&Ve&&ie(Z.key));const Ue=A.current;if(Z.target!==Ue||!Jq.includes(Z.key))return;Z.preventDefault();const Oe=R().filter(he=>!he.disabled).map(he=>he.ref.current);K3.includes(Z.key)&&Oe.reverse(),$Q(Oe)}),onBlur:de(e.onBlur,Z=>{Z.currentTarget.contains(Z.target)||(window.clearTimeout(U.current),W.current="")}),onPointerMove:de(e.onPointerMove,gd(Z=>{const H=Z.target,se=V.current!==Z.clientX;if(Z.currentTarget.contains(H)&&se){const ce=Z.clientX>V.current?"right":"left";ae.current=ce,V.current=Z.clientX}}))})))))))}),fQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),W1="MenuItem",K2="menu.itemSelect",rb=d.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=d.useRef(null),s=Qd(W1,e.__scopeMenu),l=tb(W1,e.__scopeMenu),u=Be(t,i),f=d.useRef(!1),m=()=>{const p=i.current;if(!n&&p){const g=new CustomEvent(K2,{bubbles:!0,cancelable:!0});p.addEventListener(K2,y=>r==null?void 0:r(y),{once:!0}),dx(p,g),g.defaultPrevented?f.current=!1:s.onClose()}};return d.createElement(J3,Y({},o,{ref:u,disabled:n,onClick:de(e.onClick,m),onPointerDown:p=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,p),f.current=!0},onPointerUp:de(e.onPointerUp,p=>{var g;f.current||(g=p.currentTarget)===null||g===void 0||g.click()}),onKeyDown:de(e.onKeyDown,p=>{const g=l.searchRef.current!=="";n||g&&p.key===" "||V1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})}))}),J3=d.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=tb(W1,n),l=Y3(n),u=d.useRef(null),f=Be(t,u),[m,p]=d.useState(!1),[g,y]=d.useState("");return d.useEffect(()=>{const b=u.current;if(b){var S;y(((S=b.textContent)!==null&&S!==void 0?S:"").trim())}},[i.children]),d.createElement(md.ItemSlot,{scope:n,disabled:r,textValue:o??g},d.createElement(JP,Y({asChild:!0},l,{focusable:!r}),d.createElement(Pe.div,Y({role:"menuitem","data-highlighted":m?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:f,onPointerMove:de(e.onPointerMove,gd(b=>{r?s.onItemLeave(b):(s.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus())})),onPointerLeave:de(e.onPointerLeave,gd(b=>s.onItemLeave(b))),onFocus:de(e.onFocus,()=>p(!0)),onBlur:de(e.onBlur,()=>p(!1))}))))}),hQ=d.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return d.createElement(tA,{scope:e.__scopeMenu,checked:n},d.createElement(rb,Y({role:"menuitemcheckbox","aria-checked":am(n)?"mixed":n},o,{ref:t,"data-state":ob(n),onSelect:de(o.onSelect,()=>r==null?void 0:r(am(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[$te,mQ]=za(pQ,{value:void 0,onValueChange:()=>{}}),gQ="MenuRadioItem",vQ=d.forwardRef((e,t)=>{const{value:n,...r}=e,o=mQ(gQ,e.__scopeMenu),i=n===o.value;return d.createElement(tA,{scope:e.__scopeMenu,checked:i},d.createElement(rb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":ob(i),onSelect:de(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),eA="MenuItemIndicator",[tA,yQ]=za(eA,{checked:!1}),wQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=yQ(eA,n);return d.createElement(Sn,{present:r||am(i.checked)||i.checked===!0},d.createElement(Pe.span,Y({},o,{ref:t,"data-state":ob(i.checked)})))}),xQ=d.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return d.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),nA="MenuSub",[bQ,rA]=za(nA),SQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Us(nA,t),s=gg(t),[l,u]=d.useState(null),[f,m]=d.useState(null),p=Ft(o);return d.useEffect(()=>(i.open===!1&&p(!1),()=>p(!1)),[i.open,p]),d.createElement(jd,s,d.createElement(X3,{scope:t,open:r,onOpenChange:p,content:f,onContentChange:m},d.createElement(bQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},_h="MenuSubTrigger",_Q=d.forwardRef((e,t)=>{const n=Us(_h,e.__scopeMenu),r=Qd(_h,e.__scopeMenu),o=rA(_h,e.__scopeMenu),i=tb(_h,e.__scopeMenu),s=d.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,f={__scopeMenu:e.__scopeMenu},m=d.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return d.useEffect(()=>m,[m]),d.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),d.createElement(Z3,Y({asChild:!0},f),d.createElement(J3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":oA(n.open)},e,{ref:Nm(t,o.onTriggerChange),onClick:p=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:de(e.onPointerMove,gd(p=>{i.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),m()},100))})),onPointerLeave:de(e.onPointerLeave,gd(p=>{var g;m();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var b;const S=(b=n.content)===null||b===void 0?void 0:b.dataset.side,E=S==="right",_=E?-5:5,x=y[E?"left":"right"],C=y[E?"right":"left"];i.onPointerGraceIntentChange({area:[{x:p.clientX+_,y:p.clientY},{x,y:y.top},{x:C,y:y.top},{x:C,y:y.bottom},{x,y:y.bottom}],side:S}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(p),p.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:de(e.onKeyDown,p=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&p.key===" ")&&eQ[r.dir].includes(p.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),p.preventDefault()}})})))}),EQ="MenuSubContent",CQ=d.forwardRef((e,t)=>{const n=Q3(bo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Us(bo,e.__scopeMenu),s=Qd(bo,e.__scopeMenu),l=rA(EQ,e.__scopeMenu),u=d.useRef(null),f=Be(t,u);return d.createElement(md.Provider,{scope:e.__scopeMenu},d.createElement(Sn,{present:r||i.open},d.createElement(md.Slot,{scope:e.__scopeMenu},d.createElement(nb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:f,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;s.isUsingKeyboardRef.current&&((p=u.current)===null||p===void 0||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:de(e.onFocusOutside,m=>{m.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:de(e.onEscapeKeyDown,m=>{s.onClose(),m.preventDefault()}),onKeyDown:de(e.onKeyDown,m=>{const p=m.currentTarget.contains(m.target),g=tQ[s.dir].includes(m.key);if(p&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),m.preventDefault()}})})))))});function oA(e){return e?"open":"closed"}function am(e){return e==="indeterminate"}function ob(e){return am(e)?"indeterminate":e?"checked":"unchecked"}function $Q(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function RQ(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(f=>f===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=RQ(e,Math.max(i,0));o.length===1&&(s=s.filter(f=>f!==n));const u=s.find(f=>f.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function TQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=m>r&&n<(f-l)*(r-u)/(m-u)+l&&(o=!o)}return o}function PQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return TQ(n,t)}function gd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const AQ=iQ,MQ=Z3,OQ=aQ,NQ=cQ,DQ=fQ,IQ=rb,LQ=hQ,FQ=vQ,jQ=wQ,zQ=xQ,BQ=SQ,UQ=_Q,VQ=CQ,iA="DropdownMenu",[WQ,Rte]=Mn(iA,[G3]),_r=G3(),[HQ,sA]=WQ(iA),KQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=_r(t),f=d.useRef(null),[m=!1,p]=Zr({prop:o,defaultProp:i,onChange:s});return d.createElement(HQ,{scope:t,triggerId:nr(),triggerRef:f,contentId:nr(),open:m,onOpenChange:p,onOpenToggle:d.useCallback(()=>p(g=>!g),[p]),modal:l},d.createElement(AQ,Y({},u,{open:m,onOpenChange:p,dir:r,modal:l}),n))},GQ="DropdownMenuTrigger",YQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=sA(GQ,n),s=_r(n);return d.createElement(MQ,Y({asChild:!0},s),d.createElement(Pe.button,Y({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:Nm(t,i.triggerRef),onPointerDown:de(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:de(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),XQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=_r(t);return d.createElement(OQ,Y({},r,n))},ZQ="DropdownMenuContent",qQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=sA(ZQ,n),i=_r(n),s=d.useRef(!1);return d.createElement(NQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:de(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:de(e.onInteractOutside,l=>{const u=l.detail.originalEvent,f=u.button===0&&u.ctrlKey===!0,m=u.button===2||f;(!o.modal||m)&&(s.current=!0)}),style:{...e.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)"}}))}),QQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(zQ,Y({},o,r,{ref:t}))}),oJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=_r(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return d.createElement(BQ,Y({},s,{open:l,onOpenChange:u}),n)},iJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(UQ,Y({},o,r,{ref:t}))}),sJ=d.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=_r(n);return d.createElement(VQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),aJ=KQ,lJ=YQ,cJ=XQ,aA=qQ,lA=QQ,cA=JQ,uA=eJ,dA=tJ,fA=nJ,hA=rJ,uJ=oJ,pA=iJ,mA=sJ,dJ=aJ,fJ=lJ,G2=uJ,H1=d.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(pA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(tz,{className:"ml-auto h-4 w-4"})]}));H1.displayName=pA.displayName;const K1=d.forwardRef(({className:e,...t},n)=>v.jsx(mA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));K1.displayName=mA.displayName;const gA=d.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(cJ,{children:v.jsx(aA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));gA.displayName=aA.displayName;const fl=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(cA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));fl.displayName=cA.displayName;const hJ=d.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(uA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(yT,{className:"h-4 w-4"})})}),t]}));hJ.displayName=uA.displayName;const pJ=d.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(dA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(fA,{children:v.jsx(sz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=dA.displayName;const mJ=d.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(lA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));mJ.displayName=lA.displayName;const gJ=d.forwardRef(({className:e,...t},n)=>v.jsx(hA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));gJ.displayName=hA.displayName;const Y2={RemoveBG:{IconClass:HC,showName:"RemoveBG"},AnimeSeg:{IconClass:HC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:ZT,showName:"RealESRGAN"},GFPGAN:{IconClass:KC,showName:"GFPGAN"},RestoreFormer:{IconClass:KC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:rV,showName:"Interactive Segmentation"}},vJ=()=>{const[e,t,n,r]=bt(f=>[f.file,f.serverConfig.plugins,f.updateInteractiveSegState,f.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(f,m)=>{m==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(f,m)},s=()=>v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(ZT,{}),"RealESRGAN"]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(fl,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=f=>{const{IconClass:m,showName:p}=Y2[f.name];return v.jsxs(G2,{children:[v.jsx(H1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})}),v.jsxs(K1,{children:[v.jsx(fl,{onClick:()=>i(!1,f.name),children:"Remove Background"}),v.jsx(fl,{onClick:()=>i(!0,f.name),children:"Generate Mask"})]})]},f.name)},u=()=>t.map(f=>{const{IconClass:m,showName:p}=Y2[f.name];return f.name==="RealESRGAN"?s():f.name==="RemoveBG"||f.name==="AnimeSeg"?l(f):v.jsx(fl,{onClick:()=>i(!1,f.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(m,{className:"p-1"}),p]})},f.name)});return v.jsxs(dJ,{modal:!1,children:[v.jsx(fJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(KU,{strokeWidth:1})})}),v.jsx(gA,{side:"bottom",align:"start",children:u()})]})},yJ=Cx,wJ=yP,xJ=$x,vA=d.forwardRef(({className:e,...t},n)=>v.jsx(Bd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));vA.displayName=Bd.displayName;const bJ=Dm("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),yA=d.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(xJ,{children:[v.jsx(vA,{}),v.jsx(Ud,{ref:o,className:Ce(bJ({side:e}),t),...r,children:n})]}));yA.displayName=Ud.displayName;const wA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});wA.displayName="SheetHeader";const SJ=d.forwardRef(({className:e,...t},n)=>v.jsx(Vd,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));SJ.displayName=Vd.displayName;const _J=d.forwardRef(({className:e,...t},n)=>v.jsx(Wd,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Wd.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(XT,{asChild:!0,children:v.jsx(Zx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(Sx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(wn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),EJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(go,{className:"w-[100px]",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Qw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]})]})},xA=d.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));xA.displayName="Textarea";const Eh=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(wn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},CJ=()=>{const[e,t,n,r,o,i,s,l,u,f,m]=bt(N=>[N.serverConfig.samplers,N.settings,N.paintByExampleFile,N.getIsProcessing(),N.updateSettings,N.runInpainting,N.updateAppState,N.updateExtenderByBuiltIn,N.updateExtenderDirection,N.adjustMask,N.clearMask]),[p,g]=Px(n),y=d.useRef(null);NP(y,()=>{y!=null&&y.current&&y.current.blur()});const b=N=>{N.key==="Enter"&&N.ctrlKey&&t.prompt.length!==0&&i()},S=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:N=>{o({showCropper:N}),N&&o({showExtender:!1})}})]}),E=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:N=>{o({enableControlnet:N})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:N=>o({controlnetConditioningScale:N[0]/100})}),v.jsx(Yn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:N=>{o({controlnetConditioningScale:N})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(Uo,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:N=>{o({controlnetMethod:N})},disabled:!t.enableControlnet,children:[v.jsx(go,{children:v.jsx(Vo,{placeholder:"Select control method"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(t.model.controlnets).map(N=>v.jsx(yo,{value:N,children:N.split("/")[1]},N))})})]})})]}),v.jsx(gn,{})]}):null,_=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:N=>{o({enableLCMLora:N})}})]}),v.jsx(gn,{})]}):null,x=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:N=>{o({enableFreeu:N})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,s2:N}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b1:N}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Yn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:N=>{o({freeuConfig:{...t.freeuConfig,b2:N}})}})]})]})]}),v.jsx(gn,{})]}):null,C=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(xA,{ref:y,rows:4,onKeyUp:b,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:N=>{N.preventDefault(),N.stopPropagation();const ie=N.target;o({negativePrompt:ie.value})}})})]}):null,R=()=>t.model.name!==Gk?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(f1,{tooltip:"Upload example image",onFileUpload:N=>{s({paintByExampleFile:N})},children:v.jsx(qT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:p.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(wn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==uF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:N=>o({p2pImageGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({p2pImageGuidanceScale:N})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:N=>o({sdStrength:N[0]/100})}),v.jsx(Yn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:N=>{o({sdStrength:N})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:N=>{o({showExtender:N}),N&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(Uo,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:N=>{u(N)},children:[v.jsx(go,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(Vo,{placeholder:"Select axis"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Ln).map(N=>v.jsx(yo,{value:N,children:N},N))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(Eh,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(Eh,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(Eh,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(Eh,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(gn,{})]}):null,D=()=>t.model.name!==dF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(Uo,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:N=>{o({powerpaintTask:N})},disabled:t.showExtender,children:[v.jsx(go,{className:"w-[140px]",children:v.jsx(Vo,{placeholder:"Select task"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:[Ol.text_guided,Ol.object_remove,Ol.shape_guided].map(N=>v.jsx(yo,{value:N,children:N},N))})})]})]}),U=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:N=>o({sdSteps:N[0]})}),v.jsx(Yn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:N=>{o({sdSteps:N})}})]})]}),W=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:N=>o({sdGuidanceScale:N[0]/100})}),v.jsx(Yn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:N=>{o({sdGuidanceScale:N})}})]})]}),q=()=>t.model.name===fF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(Uo,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:N=>{o({sdSampler:N})},children:[v.jsx(go,{className:"w-[175px] text-xs",children:v.jsx(Vo,{placeholder:"Select sampler"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:e.map(N=>v.jsx(yo,{value:N,className:"text-xs",children:N},N))})})]})]}),X=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:N=>{o({seedFixed:N})}}),v.jsx(Yn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:N=>{o({seed:N})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:N=>o({sdMaskBlur:N[0]})}),v.jsx(Yn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:N=>{o({sdMaskBlur:N})}})]})]}),V=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:N=>{o({sdMatchHistograms:N})}})]}),v.jsx(gn,{})]}),F=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:N=>o({adjustMaskKernelSize:N[0]})}),v.jsx(Yn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:N=>{o({adjustMaskKernelSize:N})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(wn,{variant:"outline",className:"p-1 h-8",onClick:()=>f("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(wn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:m,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(gn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[S(),A(),F(),D(),U(),W(),P(),M(),q(),X(),C(),v.jsx(gn,{}),E(),_(),ae(),V(),x(),R()]})},$J=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Uo,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(go,{className:"w-[160px]",children:v.jsx(Vo,{placeholder:"Select flag"})}),v.jsx(vo,{align:"end",children:v.jsx(vi,{children:Object.values(Jw).map(n=>v.jsx(yo,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Yn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},RJ=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=OP(!0);if(Zn("c",()=>{r()}),e.model.name!==sC&&e.model.name!==aC&&e.model.model_type===fs)return null;const o=()=>e.model.name===sC?v.jsx(EJ,{}):e.model.name===aC?v.jsx($J,{}):v.jsx(CJ,{});return v.jsxs(yJ,{open:n,modal:!1,children:[v.jsx(wJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(wn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(GU,{strokeWidth:1})})}),v.jsxs(yA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(wA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(wn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(gn,{})]}),v.jsx(ag,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Jo=Object.create(null);Jo.open="0";Jo.close="1";Jo.ping="2";Jo.pong="3";Jo.message="4";Jo.upgrade="5";Jo.noop="6";const op=Object.create(null);Object.keys(Jo).forEach(e=>{op[Jo[e]]=e});const G1={type:"error",data:"parser error"},bA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",SA=typeof ArrayBuffer=="function",_A=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,ib=({type:e,data:t},n,r)=>bA&&t instanceof Blob?n?r(t):X2(t,r):SA&&(t instanceof ArrayBuffer||_A(t))?n?r(t):X2(new Blob([t]),r):r(Jo[e]+(t||"")),X2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function Z2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let z0;function kJ(e,t){if(bA&&e.data instanceof Blob)return e.data.arrayBuffer().then(Z2).then(t);if(SA&&(e.data instanceof ArrayBuffer||_A(e.data)))return t(Z2(e.data));ib(e,!1,n=>{z0||(z0=new TextEncoder),t(z0.encode(n))})}const q2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_u=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const f=new ArrayBuffer(t),m=new Uint8Array(f);for(r=0;r>4,m[o++]=(s&15)<<4|l>>2,m[o++]=(l&3)<<6|u&63;return f},PJ=typeof ArrayBuffer=="function",sb=(e,t)=>{if(typeof e!="string")return{type:"message",data:EA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:AJ(e.substring(1),t)}:op[n]?e.length>1?{type:op[n],data:e.substring(1)}:{type:op[n]}:G1},AJ=(e,t)=>{if(PJ){const n=TJ(e);return EA(n,t)}else return{base64:!0,data:e}},EA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},CA="",MJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{ib(i,!1,l=>{r[s]=l,++o===n&&t(r.join(CA))})})},OJ=(e,t)=>{const n=e.split(CA),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let B0;function Ch(e){return e.reduce((t,n)=>t+n.length,0)}function $h(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(G1);break}o=m*Math.pow(2,32)+f.getUint32(4),r=3}else{if(Ch(n)e){l.enqueue(G1);break}}}})}const $A=4;function qt(e){if(e)return IJ(e)}function IJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const LJ=Br.setTimeout,FJ=Br.clearTimeout;function vg(e,t){t.useNativeTimers?(e.setTimeoutFn=LJ.bind(Br),e.clearTimeoutFn=FJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const jJ=1.33;function zJ(e){return typeof e=="string"?BJ(e):Math.ceil((e.byteLength||e.size)*jJ)}function BJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function UJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function VJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function TA(){const e=e$(+new Date);return e!==J2?(Q2=0,J2=e):e+"."+e$(Q2++)}for(;Rh{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,MJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=TA()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Xo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Xo extends qt{constructor(t,n){super(),vg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=RA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new AA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Xo.requestsCount++,Xo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=GJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Xo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Xo.requestsCount=0;Xo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",t$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,t$,!1)}}function t$(){for(let e in Xo.requests)Xo.requests.hasOwnProperty(e)&&Xo.requests[e].abort()}const lb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),kh=Br.WebSocket||Br.MozWebSocket,n$=!0,ZJ="arraybuffer",r$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class qJ extends ab{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=r$?{}:RA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=n$&&!r$?n?new kh(t,n):new kh(t):new kh(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{n$&&this.ws.send(i)}catch{}o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=TA()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!kh}}class QJ extends ab{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=DJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=NJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&lb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const JJ={websocket:qJ,webtransport:QJ,polling:XJ},eee=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function X1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=eee.exec(e||""),i={},s=14;for(;s--;)i[tee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=nee(i,i.path),i.queryKey=ree(i,i.query),i}function nee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function ree(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let MA=class hl extends qt{constructor(t,n={}){super(),this.binaryType=ZJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=X1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=X1(n.host).host),vg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=VJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=$A,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new JJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&hl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;hl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",p=>{if(!r)if(p.type==="pong"&&p.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;hl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(m(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,m(),n.close(),n=null)}const s=p=>{const g=new Error("probe error: "+p);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function f(p){n&&p.name!==n.name&&i()}const m=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",f)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",f),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",hl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){hl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,OA=Object.prototype.toString,aee=typeof Blob=="function"||typeof Blob<"u"&&OA.call(Blob)==="[object BlobConstructor]",lee=typeof File=="function"||typeof File<"u"&&OA.call(File)==="[object FileConstructor]";function cb(e){return iee&&(e instanceof ArrayBuffer||see(e))||aee&&e instanceof Blob||lee&&e instanceof File}function ip(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ac.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Ac.prototype.reset=function(){this.attempts=0};Ac.prototype.setMin=function(e){this.ms=e};Ac.prototype.setMax=function(e){this.max=e};Ac.prototype.setJitter=function(e){this.jitter=e};class Q1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,vg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Ac({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||mee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new MA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){lb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new NA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const gu={};function sp(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=oee(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=gu[o]&&i in gu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Q1(r,t):(gu[o]||(gu[o]=new Q1(r,t)),u=gu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(sp,{Manager:Q1,Socket:NA,io:sp,connect:sp});const DA="Progress",yg=100,[vee,kte]=Mn(DA),[yee,wee]=vee(DA),IA=d.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=See,...s}=e,l=J1(o)?o:yg,u=FA(r,l)?r:null,f=lm(u)?i(u,l):void 0;return d.createElement(yee,{scope:n,value:u,max:l},d.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":lm(u)?u:void 0,"aria-valuetext":f,role:"progressbar","data-state":LA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});IA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!J1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=J1(e.max)?e.max:yg;return r!=null&&!FA(r,i)?new Error(Eee(o,n)):null}};const xee="ProgressIndicator",bee=d.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=wee(xee,r);return d.createElement(Pe.div,Y({"data-state":LA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function See(e,t){return`${Math.round(e/t*100)}%`}function LA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function lm(e){return typeof e=="number"}function J1(e){return lm(e)&&!isNaN(e)&&e>0}function FA(e,t){return lm(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${yg}\`.`}function Eee(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${yg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const jA=IA,Cee=bee,zA=d.forwardRef(({className:e,value:t,...n},r)=>v.jsx(jA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Cee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));zA.displayName=jA.displayName;const $ee="",Zi=sp($ee),Ree=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=d.useState(!1),[i,s]=d.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return d.useEffect(()=>(Zi.on("connect",()=>{o(!0)}),Zi.on("disconnect",()=>{o(!1)}),Zi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Zi.on("diffusion_finish",()=>{s(0)}),()=>{Zi.off("connect"),Zi.off("disconnect"),Zi.off("diffusion_progress"),Zi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(zA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return d.useEffect(()=>{(async()=>{const r=await Uj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(vJ,{}),v.jsx(qq,{})]}),v.jsx(Wq,{}),v.jsx(Ree,{}),v.jsx(RJ,{}),e?v.jsx(Zq,{file:e}):v.jsx(v.Fragment,{})]})},Tee=()=>{const[e,t]=d.useState(window.innerWidth),n=d.useCallback(()=>{t(window.innerWidth)},[]);if(d.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Pee(e){const{onSelection:t}=e,[n]=d.useState(`file-upload-${Math.random().toString()}`),r=Tee();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const BA="ToastProvider",[db,Aee,Mee]=Gd("Toast"),[UA,Tte]=Mn("Toast",[Mee]),[Oee,wg]=UA(BA),VA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=d.useState(null),[f,m]=d.useState(0),p=d.useRef(!1),g=d.useRef(!1);return d.createElement(db.Provider,{scope:t},d.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:f,viewport:l,onViewportChange:u,onToastAdd:d.useCallback(()=>m(y=>y+1),[]),onToastRemove:d.useCallback(()=>m(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:g},s))};VA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${BA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Nee="ToastViewport",Dee=["F8"],ew="toast.viewportPause",tw="toast.viewportResume",Iee=d.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Dee,label:o="Notifications ({hotkey})",...i}=e,s=wg(Nee,n),l=Aee(n),u=d.useRef(null),f=d.useRef(null),m=d.useRef(null),p=d.useRef(null),g=Be(t,p,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),b=s.toastCount>0;d.useEffect(()=>{const E=_=>{var x;r.every(R=>_[R]||_.code===R)&&((x=p.current)===null||x===void 0||x.focus())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[r]),d.useEffect(()=>{const E=u.current,_=p.current;if(b&&E&&_){const x=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(ew);_.dispatchEvent(M),s.isClosePausedRef.current=!0}},C=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(tw);_.dispatchEvent(M),s.isClosePausedRef.current=!1}},R=M=>{!E.contains(M.relatedTarget)&&C()},P=()=>{E.contains(document.activeElement)||C()};return E.addEventListener("focusin",x),E.addEventListener("focusout",R),E.addEventListener("pointermove",x),E.addEventListener("pointerleave",P),window.addEventListener("blur",x),window.addEventListener("focus",C),()=>{E.removeEventListener("focusin",x),E.removeEventListener("focusout",R),E.removeEventListener("pointermove",x),E.removeEventListener("pointerleave",P),window.removeEventListener("blur",x),window.removeEventListener("focus",C)}}},[b,s.isClosePausedRef]);const S=d.useCallback(({tabbingDirection:E})=>{const x=l().map(C=>{const R=C.ref.current,P=[R,...Qee(R)];return E==="forwards"?P:P.reverse()});return(E==="forwards"?x.reverse():x).flat()},[l]);return d.useEffect(()=>{const E=p.current;if(E){const _=x=>{const C=x.altKey||x.ctrlKey||x.metaKey;if(x.key==="Tab"&&!C){const D=document.activeElement,U=x.shiftKey;if(x.target===E&&U){var P;(P=f.current)===null||P===void 0||P.focus();return}const X=S({tabbingDirection:U?"backwards":"forwards"}),ae=X.findIndex(V=>V===D);if(U0(X.slice(ae+1)))x.preventDefault();else{var M,A;U?(M=f.current)===null||M===void 0||M.focus():(A=m.current)===null||A===void 0||A.focus()}}};return E.addEventListener("keydown",_),()=>E.removeEventListener("keydown",_)}},[l,S]),d.createElement(EB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:b?void 0:"none"}},b&&d.createElement(i$,{ref:f,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"forwards"});U0(E)}}),d.createElement(db.Slot,{scope:n},d.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),b&&d.createElement(i$,{ref:m,onFocusFromOutsideViewport:()=>{const E=S({tabbingDirection:"backwards"});U0(E)}}))}),Lee="ToastFocusProxy",i$=d.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=wg(Lee,n);return d.createElement(Hm,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),xg="Toast",Fee="toast.swipeStart",jee="toast.swipeMove",zee="toast.swipeCancel",Bee="toast.swipeEnd",Uee=d.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return d.createElement(Sn,{present:n||l},d.createElement(WA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:de(e.onSwipeStart,f=>{f.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:de(e.onSwipeMove,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","move"),f.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:de(e.onSwipeCancel,f=>{f.currentTarget.setAttribute("data-swipe","cancel"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:de(e.onSwipeEnd,f=>{const{x:m,y:p}=f.detail.delta;f.currentTarget.setAttribute("data-swipe","end"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),f.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),f.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${m}px`),f.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),u(!1)})})))}),[Vee,Wee]=UA(xg,{onClose(){}}),WA=d.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:f,onSwipeStart:m,onSwipeMove:p,onSwipeCancel:g,onSwipeEnd:y,...b}=e,S=wg(xg,n),[E,_]=d.useState(null),x=Be(t,V=>_(V)),C=d.useRef(null),R=d.useRef(null),P=o||S.duration,M=d.useRef(0),A=d.useRef(P),D=d.useRef(0),{onToastAdd:U,onToastRemove:W}=S,q=Ft(()=>{var V;(E==null?void 0:E.contains(document.activeElement))&&((V=S.viewport)===null||V===void 0||V.focus()),s()}),X=d.useCallback(V=>{!V||V===1/0||(window.clearTimeout(D.current),M.current=new Date().getTime(),D.current=window.setTimeout(q,V))},[q]);d.useEffect(()=>{const V=S.viewport;if(V){const F=()=>{X(A.current),f==null||f()},N=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(D.current),u==null||u()};return V.addEventListener(ew,N),V.addEventListener(tw,F),()=>{V.removeEventListener(ew,N),V.removeEventListener(tw,F)}}},[S.viewport,P,u,f,X]),d.useEffect(()=>{i&&!S.isClosePausedRef.current&&X(P)},[i,P,S.isClosePausedRef,X]),d.useEffect(()=>(U(),()=>W()),[U,W]);const ae=d.useMemo(()=>E?YA(E):null,[E]);return S.viewport?d.createElement(d.Fragment,null,ae&&d.createElement(Hee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),d.createElement(Vee,{scope:n,onClose:q},Is.createPortal(d.createElement(db.ItemSlot,{scope:n},d.createElement(_B,{asChild:!0,onEscapeKeyDown:de(l,()=>{S.isFocusedToastEscapeKeyDownRef.current||q(),S.isFocusedToastEscapeKeyDownRef.current=!1})},d.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":S.swipeDirection},b,{ref:x,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:de(e.onKeyDown,V=>{V.key==="Escape"&&(l==null||l(V.nativeEvent),V.nativeEvent.defaultPrevented||(S.isFocusedToastEscapeKeyDownRef.current=!0,q()))}),onPointerDown:de(e.onPointerDown,V=>{V.button===0&&(C.current={x:V.clientX,y:V.clientY})}),onPointerMove:de(e.onPointerMove,V=>{if(!C.current)return;const F=V.clientX-C.current.x,N=V.clientY-C.current.y,ie=!!R.current,K=["left","right"].includes(S.swipeDirection),Z=["left","up"].includes(S.swipeDirection)?Math.min:Math.max,H=K?Z(0,F):0,se=K?0:Z(0,N),ce=V.pointerType==="touch"?10:2,Ve={x:H,y:se},Ue={originalEvent:V,delta:Ve};ie?(R.current=Ve,Th(jee,p,Ue,{discrete:!1})):s$(Ve,S.swipeDirection,ce)?(R.current=Ve,Th(Fee,m,Ue,{discrete:!1}),V.target.setPointerCapture(V.pointerId)):(Math.abs(F)>ce||Math.abs(N)>ce)&&(C.current=null)}),onPointerUp:de(e.onPointerUp,V=>{const F=R.current,N=V.target;if(N.hasPointerCapture(V.pointerId)&&N.releasePointerCapture(V.pointerId),R.current=null,C.current=null,F){const ie=V.currentTarget,K={originalEvent:V,delta:F};s$(F,S.swipeDirection,S.swipeThreshold)?Th(Bee,y,K,{discrete:!0}):Th(zee,g,K,{discrete:!0}),ie.addEventListener("click",Z=>Z.preventDefault(),{once:!0})}})})))),S.viewport))):null});WA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${xg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Hee=e=>{const{__scopeToast:t,children:n,...r}=e,o=wg(xg,t),[i,s]=d.useState(!1),[l,u]=d.useState(!1);return Zee(()=>s(!0)),d.useEffect(()=>{const f=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(f)},[]),l?null:d.createElement(zd,{asChild:!0},d.createElement(Hm,r,i&&d.createElement(d.Fragment,null,o.label," ",n)))},Kee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Gee=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return d.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",HA=d.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?d.createElement(GA,{altText:n,asChild:!0},d.createElement(KA,Y({},r,{ref:t}))):null});HA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Xee="ToastClose",KA=d.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Wee(Xee,n);return d.createElement(GA,{asChild:!0},d.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:de(e.onClick,o.onClose)})))}),GA=d.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return d.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function YA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),qee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...YA(r))}}),t}function Th(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?dx(o,i):o.dispatchEvent(i)}const s$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Zee(e=()=>{}){const t=Ft(e);An(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function qee(e){return e.nodeType===e.ELEMENT_NODE}function Qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function U0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Jee=VA,XA=Iee,ZA=Uee,qA=Kee,QA=Gee,JA=HA,eM=KA,ete=Jee,tM=d.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));tM.displayName=XA.displayName;const tte=Dm("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),nM=d.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(ZA,{ref:r,className:Ce(tte({variant:t}),e),tabIndex:-1,...n}));nM.displayName=ZA.displayName;const nte=d.forwardRef(({className:e,...t},n)=>v.jsx(JA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));nte.displayName=JA.displayName;const rM=d.forwardRef(({className:e,...t},n)=>v.jsx(eM,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(wT,{className:"h-4 w-4"})}));rM.displayName=eM.displayName;const oM=d.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));oM.displayName=qA.displayName;const iM=d.forwardRef(({className:e,...t},n)=>v.jsx(QA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));iM.displayName=QA.displayName;function rte(){const{toasts:e}=Id();return v.jsxs(ete,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(nM,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(oM,{children:n}),r&&v.jsx(iM,{children:r})]}),o,v.jsx(rM,{})]},t)}),v.jsx(tM,{})]})}const ote=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ite(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=vH();d.useEffect(()=>{o&&r(o)},[o,r]),d.useEffect(()=>{t({windowSize:i})},[i]),d.useEffect(()=>{(async()=>{const y=await gT();n(y),y.isDesktop&&pF()})()},[]);const s=d.useRef(0),l=d.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),f=d.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),m=d.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],b=y.type;ote.includes(b)&&r(y)}g.dataTransfer.clearData()}},[]),p=d.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,b=[].slice.call(y).filter(_=>_.type.indexOf("image")!==-1);if(b.length===0)return;g.preventDefault(),g.stopPropagation();const E=b[0].getAsFile();E&&r(E)},[]);return d.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",f),window.addEventListener("dragover",l),window.addEventListener("drop",m),window.addEventListener("paste",p),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",f),window.removeEventListener("dragover",l),window.removeEventListener("drop",m),window.removeEventListener("paste",p)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(rte,{}),v.jsx(nZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Pee,{onSelection:async g=>{r(g)}})]})}const cm=["light","dark"],fb="(prefers-color-scheme: dark)",ste=typeof window>"u",sM=d.createContext(void 0),ate=e=>d.useContext(sM)?Fe.createElement(d.Fragment,null,e.children):Fe.createElement(cte,e),lte=["light","dark"],cte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=lte,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:f,nonce:m})=>{const[p,g]=d.useState(()=>a$(o,s)),[y,b]=d.useState(()=>a$(o)),S=u?Object.values(u):i,E=d.useCallback(R=>{let P=R;if(!P)return;R==="system"&&n&&(P=l$());const M=u?u[P]:P,A=t?dte():null,D=document.documentElement;if(l==="class"?(D.classList.remove(...S),M&&D.classList.add(M)):M?D.setAttribute(l,M):D.removeAttribute(l),r){const U=cm.includes(s)?s:null,W=cm.includes(P)?P:U;D.style.colorScheme=W}A==null||A()},[]),_=d.useCallback(R=>{g(R);try{localStorage.setItem(o,R)}catch{}},[e]),x=d.useCallback(R=>{const P=l$(R);b(P),p==="system"&&n&&!e&&E("system")},[p,e]);d.useEffect(()=>{const R=window.matchMedia(fb);return R.addListener(x),x(R),()=>R.removeListener(x)},[x]),d.useEffect(()=>{const R=P=>{P.key===o&&_(P.newValue||s)};return window.addEventListener("storage",R),()=>window.removeEventListener("storage",R)},[_]),d.useEffect(()=>{E(e??p)},[e,p]);const C=d.useMemo(()=>({theme:p,setTheme:_,forcedTheme:e,resolvedTheme:p==="system"?y:p,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[p,_,e,y,n,i]);return Fe.createElement(sM.Provider,{value:C},Fe.createElement(ute,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:f,attrs:S,nonce:m}),f)},ute=d.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const f=i==="system",m=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(b=>`'${b}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,p=o?cm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(b,S=!1,E=!0)=>{const _=s?s[b]:b,x=S?b+"|| ''":`'${_}'`;let C="";return o&&E&&!S&&cm.includes(b)&&(C+=`d.style.colorScheme = '${b}';`),n==="class"?C+=S||_?`c.add(${x})`:"null":_&&(C+=`d[s](n,${x})`),C},y=e?`!function(){${m}${g(e)}}()`:r?`!function(){try{${m}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${f})){var t='${fb}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${f?"":"else{"+g(i,!1,!1)+"}"}${p}}catch(e){}}()`:`!function(){try{${m}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${p}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),a$=(e,t)=>{if(ste)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},dte=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},l$=e=>(e||(e=window.matchMedia(fb)),e.matches?"dark":"light"),fte=new pL;V0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(wL,{client:fte,children:v.jsx(ate,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(VU,{children:v.jsx(ite,{})})})})})); diff --git a/py/iopaint/web_app/assets/index-p0ivNJpo.css b/py/iopaint/web_app/assets/index-p0ivNJpo.css new file mode 100644 index 0000000..61296f4 --- /dev/null +++ b/py/iopaint/web_app/assets/index-p0ivNJpo.css @@ -0,0 +1 @@ +@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(/assets/Inter-Thin-eKObIkJC.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(/assets/Inter-ThinItalic-L6uBn3RP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLight-w5HAp5iF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(/assets/Inter-ExtraLightItalic-ZptecSuc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(/assets/Inter-Light-DFhX0qo-.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(/assets/Inter-LightItalic-fu56_DRc.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(/assets/Inter-Regular-dEFHw1tF.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(/assets/Inter-Italic-f6M78thn.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(/assets/Inter-Medium-dDRaJ8tM.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(/assets/Inter-MediumItalic-zr3roggP.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBold-PyS8DO2L.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(/assets/Inter-SemiBoldItalic-uIDb7hsH.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(/assets/Inter-Bold-srYz_-1B.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(/assets/Inter-BoldItalic-dE_gZyur.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBold-TduDdwUu.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(/assets/Inter-ExtraBoldItalic-BJafRE5I.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(/assets/Inter-Black-jiII8dog.woff2?v=4.0) format("woff2")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(/assets/Inter-BlackItalic-1413vuen.woff2?v=4.0) format("woff2")}*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}:root{--background: 0 0% 100%;--foreground: 224 71.4% 4.1%;--card: 0 0% 100%;--card-foreground: 224 71.4% 4.1%;--popover: 0 0% 100%;--popover-foreground: 224 71.4% 4.1%;--primary: 48 100% 50%;--primary-foreground: 210 20% 98%;--secondary: 220 14.3% 95.9%;--secondary-foreground: 220.9 39.3% 11%;--muted: 220 14.3% 95.9%;--muted-foreground: 220 8.9% 46.1%;--accent: 220 14.3% 95.9%;--accent-foreground: 220.9 39.3% 11%;--destructive: 0 84.2% 60.2%;--destructive-foreground: 210 20% 98%;--border: 220 13% 91%;--input: 220 13% 91%;--ring: 224 71.4% 4.1%;--radius: .5rem}[data-theme=dark]{--background: 240 10% 3.9%;--foreground: 0 0% 98%;--card: 224 71.4% 4.1%;--card-foreground: 210 20% 98%;--popover: 240 10% 3.9%;--popover-foreground: 0 0% 98%;--primary: 48 100% 50%;--primary-foreground: 220.9 39.3% 11%;--secondary: 240 3.7% 15.9%;--secondary-foreground: 0 0% 98%;--muted: 240 3.7% 15.9%;--muted-foreground: 240 5% 64.9%;--accent: 240 3.7% 15.9%;--accent-foreground: 0 0% 98%;--destructive: 0 62.8% 30.6%;--destructive-foreground: 0 85.7% 97.3%;--border: 240 3.7% 15.9%;--input: 240 3.7% 15.9%;--ring: 240 4.9% 83.9%}*{border-color:hsl(var(--border))}body{background-color:hsl(var(--background));color:hsl(var(--foreground))}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0}.pointer-events-none{pointer-events:none}.pointer-events-auto{pointer-events:auto}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{top:0;right:0;bottom:0;left:0}.inset-x-0{left:0;right:0}.inset-y-0{top:0;bottom:0}.bottom-0{bottom:0}.bottom-5{bottom:1.25rem}.bottom-6{bottom:1.5rem}.left-0{left:0}.left-1\/2{left:50%}.left-2{left:.5rem}.left-\[24px\]{left:24px}.left-\[50\%\]{left:50%}.left-\[8px\]{left:8px}.right-0{right:0}.right-1{right:.25rem}.right-10{right:2.5rem}.right-2{right:.5rem}.right-4{right:1rem}.right-6{right:1.5rem}.top-0{top:0}.top-1{top:.25rem}.top-4{top:1rem}.top-\[0\]{top:0}.top-\[50\%\]{top:50%}.top-\[68px\]{top:68px}.z-10{z-index:10}.z-20{z-index:20}.z-50{z-index:50}.z-\[100\]{z-index:100}.z-\[2\]{z-index:2}.z-\[4\]{z-index:4}.m-3{margin:.75rem}.-mx-1{margin-left:-.25rem;margin-right:-.25rem}.my-1{margin-top:.25rem;margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-8{margin-bottom:2rem}.mb-\[-6px\]{margin-bottom:-6px}.ml-\[-6px\]{margin-left:-6px}.ml-auto{margin-left:auto}.mr-8{margin-right:2rem}.mr-\[-6px\]{margin-right:-6px}.mt-0{margin-top:0}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-\[-6px\]{margin-top:-6px}.mt-\[60px\]{margin-top:60px}.block{display:block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.aspect-square{aspect-ratio:1 / 1}.h-1{height:.25rem}.h-1\.5{height:.375rem}.h-10{height:2.5rem}.h-2{height:.5rem}.h-2\.5{height:.625rem}.h-3{height:.75rem}.h-3\.5{height:.875rem}.h-4{height:1rem}.h-4\/5{height:80%}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-7{height:1.75rem}.h-8{height:2rem}.h-9{height:2.25rem}.h-\[10px\]{height:10px}.h-\[12px\]{height:12px}.h-\[1px\]{height:1px}.h-\[20px\]{height:20px}.h-\[240px\]{height:240px}.h-\[32px\]{height:32px}.h-\[600px\]{height:600px}.h-\[60px\]{height:60px}.h-\[var\(--radix-select-trigger-height\)\]{height:var(--radix-select-trigger-height)}.h-full{height:100%}.h-px{height:1px}.h-screen{height:100vh}.max-h-96{max-height:24rem}.max-h-\[200px\]{max-height:200px}.max-h-\[8rem\]{max-height:8rem}.max-h-screen{max-height:100vh}.min-h-\[32px\]{min-height:32px}.min-h-\[60px\]{min-height:60px}.min-h-screen{min-height:100vh}.w-14{width:3.5rem}.w-2{width:.5rem}.w-2\.5{width:.625rem}.w-3{width:.75rem}.w-3\.5{width:.875rem}.w-3\/4{width:75%}.w-4{width:1rem}.w-48{width:12rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-72{width:18rem}.w-8{width:2rem}.w-9{width:2.25rem}.w-\[100px\]{width:100px}.w-\[10px\]{width:10px}.w-\[12px\]{width:12px}.w-\[140px\]{width:140px}.w-\[160px\]{width:160px}.w-\[175px\]{width:175px}.w-\[180px\]{width:180px}.w-\[1px\]{width:1px}.w-\[20px\]{width:20px}.w-\[220px\]{width:220px}.w-\[250px\]{width:250px}.w-\[300px\]{width:300px}.w-\[400px\]{width:400px}.w-\[45px\]{width:45px}.w-\[500px\]{width:500px}.w-\[510px\]{width:510px}.w-\[60px\]{width:60px}.w-\[65px\]{width:65px}.w-\[6px\]{width:6px}.w-auto{width:auto}.w-full{width:100%}.w-screen{width:100vw}.min-w-\[600px\]{min-width:600px}.min-w-\[8rem\]{min-width:8rem}.min-w-\[var\(--radix-select-trigger-width\)\]{min-width:var(--radix-select-trigger-width)}.max-w-3xl{max-width:48rem}.max-w-6xl{max-width:72rem}.max-w-\[200px\]{max-width:200px}.max-w-lg{max-width:32rem}.max-w-sm{max-width:24rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink{flex-shrink:1}.shrink-0{flex-shrink:0}.grow{flex-grow:1}.origin-top-left{transform-origin:top left}.-translate-x-1\/2,.translate-x-\[-50\%\]{--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.translate-y-\[-50\%\]{--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-default{cursor:default}.cursor-ew-resize{cursor:ew-resize}.cursor-ne-resize{cursor:ne-resize}.cursor-ns-resize{cursor:ns-resize}.cursor-nw-resize{cursor:nw-resize}.cursor-pointer{cursor:pointer}.cursor-se-resize{cursor:se-resize}.cursor-sw-resize{cursor:sw-resize}.touch-none{touch-action:none}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-col-reverse{flex-direction:column-reverse}.items-center{align-items:center}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.gap-\[12px\]{gap:12px}.gap-\[18px\]{gap:18px}.gap-\[8px\]{gap:8px}.gap-y-4{row-gap:1rem}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-8>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(2rem * var(--tw-space-x-reverse));margin-left:calc(2rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.overflow-y-hidden{overflow-y:hidden}.whitespace-nowrap{white-space:nowrap}.rounded-\[14px\]{border-radius:14px}.rounded-\[3rem\]{border-radius:3rem}.rounded-\[50\%\]{border-radius:50%}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-\[1px\]{border-width:1px}.border-\[2px\]{border-width:2px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-solid{border-style:solid}.border-\[\#ffcc00\]{--tw-border-opacity: 1;border-color:rgb(255 204 0 / var(--tw-border-opacity))}.border-\[dashed\]{border-color:dashed}.border-\[solid\]{border-color:solid}.border-destructive{border-color:hsl(var(--destructive))}.border-input{border-color:hsl(var(--input))}.border-primary{border-color:hsl(var(--primary))}.border-primary\/60{border-color:hsl(var(--primary) / .6)}.border-transparent{border-color:transparent}.border-l-transparent{border-left-color:transparent}.border-t-transparent{border-top-color:transparent}.bg-\[\#ffcc00bb\]{background-color:#fc0b}.bg-\[rgba\(21\,_215\,_121\,_0\.936\)\]{background-color:#15d779ef}.bg-\[rgba\(237\,_49\,_55\,_0\.942\)\]{background-color:#ed3137f0}.bg-background{background-color:hsl(var(--background))}.bg-background\/70{background-color:hsl(var(--background) / .7)}.bg-background\/80{background-color:hsl(var(--background) / .8)}.bg-border{background-color:hsl(var(--border))}.bg-destructive{background-color:hsl(var(--destructive))}.bg-muted{background-color:hsl(var(--muted))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-secondary{background-color:hsl(var(--secondary))}.bg-transparent{background-color:transparent}.bg-\[radial-gradient\(circle_at_1px_1px\,_\#8e8e8e8e_1px\,_transparent_0\)\]{background-image:radial-gradient(circle at 1px 1px,#8e8e8e8e 1px,transparent 0)}.bg-repeat{background-repeat:repeat}.fill-current{fill:currentColor}.fill-primary{fill:hsl(var(--primary))}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-16{padding:4rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-\[1px\]{padding:1px}.p-\[8px\]{padding:8px}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-\[6px\]{padding-top:6px;padding-bottom:6px}.pb-4{padding-bottom:1rem}.pl-2{padding-left:.5rem}.pl-4{padding-left:1rem}.pl-8{padding-left:2rem}.pl-\[30px\]{padding-left:30px}.pl-\[8px\]{padding-left:8px}.pr-1{padding-right:.25rem}.pr-2{padding-right:.5rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-6{padding-right:1.5rem}.pr-8{padding-right:2rem}.pr-\[8px\]{padding-right:8px}.pt-0{padding-top:0}.pt-4{padding-top:1rem}.text-center{text-align:center}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.8rem\]{font-size:.8rem}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-none{line-height:1}.tracking-tight{letter-spacing:-.025em}.tracking-widest{letter-spacing:.1em}.text-destructive{color:hsl(var(--destructive))}.text-destructive-foreground{color:hsl(var(--destructive-foreground))}.text-foreground{color:hsl(var(--foreground))}.text-foreground\/50{color:hsl(var(--foreground) / .5)}.text-gray-200{--tw-text-opacity: 1;color:rgb(229 231 235 / var(--tw-text-opacity))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.underline-offset-4{text-underline-offset:4px}.opacity-0{opacity:0}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-90{opacity:.9}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.outline-dashed{outline-style:dashed}.outline-8{outline-width:8px}.outline-\[rgba\(255\,89\,95\,0\.31\)\]{outline-color:#ff595f4f}.outline-\[rgba\(98\,255\,179\,0\.31\)\]{outline-color:#62ffb34f}.outline-primary{outline-color:hsl(var(--primary))}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[height\]{transition-property:height;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.content-\[\'\'\]{--tw-content: "";content:var(--tw-content)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.duration-200{animation-duration:.2s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.\[background-size\:20px_20px\]{background-size:20px 20px}.\[box-shadow\:0_0_0_0_rgba\(21\,_215\,_121\,_0\.936\)\]{box-shadow:0 0 #15d779ef}.\[box-shadow\:0_0_0_9999px_rgba\(0\,_0\,_0\,_0\.5\)\]{box-shadow:0 0 0 9999px #00000080}.\[grid-area\:editor-content\]{grid-area:editor-content}.\[grid-area\:original-image-content\]{grid-area:original-image-content}.\[grid-template-areas\:\'editor-content\'\]{grid-template-areas:"editor-content"}.\[grid-template-areas\:\'original-image-content\'\]{grid-template-areas:"original-image-content"}html{font-family:Inter,"system-ui";overflow:hidden}@supports (font-variation-settings: normal){html{font-family:Inter var,"system-ui"}}.react-transform-wrapper{display:grid!important;width:100%!important;height:100%!important}.react-photo-album{padding:8px}.react-photo-album--photo{-moz-user-select:none;-webkit-user-select:none;user-select:none;border-radius:8px;transition:transform .25s,visibility .25s ease-in}.react-photo-album--photo:hover{border:1px solid var(--border);transform:scale(1.03)}.icon-button-icon-wrapper svg{stroke-width:1px}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.hover\:cursor-move:hover{cursor:move}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-primary:hover{background-color:hsl(var(--primary))}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-secondary:hover{background-color:hsl(var(--secondary))}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-primary-foreground:hover{color:hsl(var(--primary-foreground))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.focus\:h-\[120px\]:focus{height:120px}.focus\:overflow-y-auto:focus{overflow-y:auto}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:opacity-100:focus{opacity:1}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:outline-none:focus-visible{outline:2px solid transparent;outline-offset:2px}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-offset-2:focus-visible{--tw-ring-offset-width: 2px}.focus-visible\:ring-offset-background:focus-visible{--tw-ring-offset-color: hsl(var(--background))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:opacity-100{opacity:1}.group.destructive .group-\[\.destructive\]\:border-muted\/40{border-color:hsl(var(--muted) / .4)}.group.destructive .group-\[\.destructive\]\:text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:hover\:border-destructive\/30:hover{border-color:hsl(var(--destructive) / .3)}.group.destructive .group-\[\.destructive\]\:hover\:bg-destructive:hover{background-color:hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:hover\:text-destructive-foreground:hover{color:hsl(var(--destructive-foreground))}.group.destructive .group-\[\.destructive\]\:hover\:text-red-50:hover{--tw-text-opacity: 1;color:rgb(254 242 242 / var(--tw-text-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-destructive:focus{--tw-ring-color: hsl(var(--destructive))}.group.destructive .group-\[\.destructive\]\:focus\:ring-red-400:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(248 113 113 / var(--tw-ring-opacity))}.group.destructive .group-\[\.destructive\]\:focus\:ring-offset-red-600:focus{--tw-ring-offset-color: #dc2626}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-70{opacity:.7}.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-4[data-state=checked]{--tw-translate-x: 1rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked],.data-\[swipe\=cancel\]\:translate-x-0[data-swipe=cancel]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=end\]\:translate-x-\[var\(--radix-toast-swipe-end-x\)\][data-swipe=end]{--tw-translate-x: var(--radix-toast-swipe-end-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[swipe\=move\]\:translate-x-\[var\(--radix-toast-swipe-move-x\)\][data-swipe=move]{--tw-translate-x: var(--radix-toast-swipe-move-x);transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[disabled\]\:cursor-not-allowed[data-disabled]{cursor:not-allowed}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[state\=active\]\:text-foreground[data-state=active]{color:hsl(var(--foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=active\]\:shadow[data-state=active]{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[swipe\=move\]\:transition-none[data-swipe=move]{transition-property:none}.data-\[state\=closed\]\:duration-200[data-state=closed]{transition-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{transition-duration:.3s}.data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[swipe\=end\]\:animate-out[data-swipe=end]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.data-\[state\=closed\]\:fade-out-80[data-state=closed]{--tw-exit-opacity: .8}.data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-left-1\/2[data-state=closed]{--tw-exit-translate-x: -50%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed],.data-\[state\=closed\]\:slide-out-to-right-full[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=closed\]\:slide-out-to-top-\[48\%\][data-state=closed]{--tw-exit-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-left-1\/2[data-state=open]{--tw-enter-translate-x: -50%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-top-\[48\%\][data-state=open]{--tw-enter-translate-y: -48%}.data-\[state\=open\]\:slide-in-from-top-full[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-200[data-state=closed]{animation-duration:.2s}.data-\[state\=open\]\:duration-300[data-state=open]{animation-duration:.3s}:is(.dark .dark\:text-gray-600){--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity))}@media (min-width: 640px){.sm\:bottom-0{bottom:0}.sm\:right-0{right:0}.sm\:top-auto{top:auto}.sm\:mt-0{margin-top:0}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:flex-col{flex-direction:column}.sm\:justify-end{justify-content:flex-end}.sm\:space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:rounded-lg{border-radius:var(--radius)}.sm\:text-left{text-align:left}.data-\[state\=open\]\:sm\:slide-in-from-bottom-full[data-state=open]{--tw-enter-translate-y: 100%}}@media (min-width: 768px){.md\:max-w-\[420px\]{max-width:420px}}.\[\&\+div\]\:text-xs+div{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:line-clamp-1>span{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))} diff --git a/py/iopaint/web_app/assets/index-qFliSBYV.js b/py/iopaint/web_app/assets/index-qFliSBYV.js new file mode 100644 index 0000000..71fc7b1 --- /dev/null +++ b/py/iopaint/web_app/assets/index-qFliSBYV.js @@ -0,0 +1,165 @@ +var Nv=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var z=(e,t,n)=>(Nv(e,t,"read from private field"),n?n.call(e):t.get(e)),Te=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},ye=(e,t,n,r)=>(Nv(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Ff=(e,t,n,r)=>({set _(o){ye(e,t,o,n)},get _(){return z(e,t,r)}}),tt=(e,t,n)=>(Nv(e,t,"access private method"),n);function SD(e,t){for(var n=0;nr[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Yc=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lm(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var v$={exports:{}},cm={},y$={exports:{}},it={};/** + * @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. + */var bd=Symbol.for("react.element"),ED=Symbol.for("react.portal"),CD=Symbol.for("react.fragment"),$D=Symbol.for("react.strict_mode"),kD=Symbol.for("react.profiler"),RD=Symbol.for("react.provider"),TD=Symbol.for("react.context"),PD=Symbol.for("react.forward_ref"),AD=Symbol.for("react.suspense"),OD=Symbol.for("react.memo"),MD=Symbol.for("react.lazy"),LS=Symbol.iterator;function ND(e){return e===null||typeof e!="object"?null:(e=LS&&e[LS]||e["@@iterator"],typeof e=="function"?e:null)}var w$={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x$=Object.assign,b$={};function fc(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}fc.prototype.isReactComponent={};fc.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=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,e,t,"setState")};fc.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function _$(){}_$.prototype=fc.prototype;function ew(e,t,n){this.props=e,this.context=t,this.refs=b$,this.updater=n||w$}var tw=ew.prototype=new _$;tw.constructor=ew;x$(tw,fc.prototype);tw.isPureReactComponent=!0;var FS=Array.isArray,S$=Object.prototype.hasOwnProperty,nw={current:null},E$={key:!0,ref:!0,__self:!0,__source:!0};function C$(e,t,n){var r,o={},i=null,s=null;if(t!=null)for(r in t.ref!==void 0&&(s=t.ref),t.key!==void 0&&(i=""+t.key),t)S$.call(t,r)&&!E$.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(l===1)o.children=n;else if(1>>1,ge=K[le];if(0>>1;leo(We,W))Meo(fe,We)?(K[le]=fe,K[Me]=W,le=Me):(K[le]=We,K[Ue]=W,le=Ue);else if(Meo(fe,W))K[le]=fe,K[Me]=W,le=Me;else break e}}return Q}function o(K,Q){var W=K.sortIndex-Q.sortIndex;return W!==0?W:K.id-Q.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var s=Date,l=s.now();e.unstable_now=function(){return s.now()-l}}var u=[],d=[],h=1,m=null,g=3,y=!1,x=!1,_=!1,C=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function E(K){for(var Q=n(d);Q!==null;){if(Q.callback===null)r(d);else if(Q.startTime<=K)r(d),Q.sortIndex=Q.expirationTime,t(u,Q);else break;Q=n(d)}}function k(K){if(_=!1,E(K),!x)if(n(u)!==null)x=!0,L(P);else{var Q=n(d);Q!==null&&ie(k,Q.startTime-K)}}function P(K,Q){x=!1,_&&(_=!1,S(O),O=-1),y=!0;var W=g;try{for(E(Q),m=n(u);m!==null&&(!(m.expirationTime>Q)||K&&!J());){var le=m.callback;if(typeof le=="function"){m.callback=null,g=m.priorityLevel;var ge=le(m.expirationTime<=Q);Q=e.unstable_now(),typeof ge=="function"?m.callback=ge:m===n(u)&&r(u),E(Q)}else r(u);m=n(u)}if(m!==null)var Ve=!0;else{var Ue=n(d);Ue!==null&&ie(k,Ue.startTime-Q),Ve=!1}return Ve}finally{m=null,g=W,y=!1}}var M=!1,A=null,O=-1,F=5,V=-1;function J(){return!(e.unstable_now()-VK||125le?(K.sortIndex=W,t(d,K),n(u)===null&&K===n(d)&&(_?(S(O),O=-1):_=!0,ie(k,W-le))):(K.sortIndex=ge,t(u,K),x||y||(x=!0,L(P))),K},e.unstable_shouldYield=J,e.unstable_wrapCallback=function(K){var Q=g;return function(){var W=g;g=Q;try{return K.apply(this,arguments)}finally{g=W}}}})(T$);R$.exports=T$;var KD=R$.exports;/** + * @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. + */var P$=f,yr=KD;function ce(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),B0=Object.prototype.hasOwnProperty,YD=/^[: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]*$/,zS={},BS={};function GD(e){return B0.call(BS,e)?!0:B0.call(zS,e)?!1:YD.test(e)?BS[e]=!0:(zS[e]=!0,!1)}function XD(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function ZD(e,t,n,r){if(t===null||typeof t>"u"||XD(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Un(e,t,n,r,o,i,s){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=s}var xn={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){xn[e]=new Un(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];xn[t]=new Un(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){xn[e]=new Un(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){xn[e]=new Un(e,2,!1,e,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(e){xn[e]=new Un(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){xn[e]=new Un(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){xn[e]=new Un(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){xn[e]=new Un(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){xn[e]=new Un(e,5,!1,e.toLowerCase(),null,!1,!1)});var ow=/[\-:]([a-z])/g;function iw(e){return e[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(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(ow,iw);xn[t]=new Un(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!1,!1)});xn.xlinkHref=new Un("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){xn[e]=new Un(e,1,!1,e.toLowerCase(),null,!0,!0)});function sw(e,t,n,r){var o=xn.hasOwnProperty(t)?xn[t]:null;(o!==null?o.type!==0:r||!(2l||o[s]!==i[l]){var u=` +`+o[s].replace(" at new "," at ");return e.displayName&&u.includes("")&&(u=u.replace("",e.displayName)),u}while(1<=s&&0<=l);break}}}finally{Lv=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?uu(e):""}function qD(e){switch(e.tag){case 5:return uu(e.type);case 16:return uu("Lazy");case 13:return uu("Suspense");case 19:return uu("SuspenseList");case 0:case 2:case 15:return e=Fv(e.type,!1),e;case 11:return e=Fv(e.type.render,!1),e;case 1:return e=Fv(e.type,!0),e;default:return""}}function H0(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case ll:return"Fragment";case al:return"Portal";case U0:return"Profiler";case aw:return"StrictMode";case V0:return"Suspense";case W0:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case M$:return(e.displayName||"Context")+".Consumer";case O$:return(e._context.displayName||"Context")+".Provider";case lw:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case cw:return t=e.displayName||null,t!==null?t:H0(e.type)||"Memo";case Ki:t=e._payload,e=e._init;try{return H0(e(t))}catch{}}return null}function QD(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return H0(t);case 8:return t===aw?"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 t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function Ss(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function D$(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function JD(e){var t=D$(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(s){r=""+s,i.call(this,s)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(s){r=""+s},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Bf(e){e._valueTracker||(e._valueTracker=JD(e))}function I$(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=D$(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function oh(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function K0(e,t){var n=t.checked;return zt({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function VS(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=Ss(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function L$(e,t){t=t.checked,t!=null&&sw(e,"checked",t,!1)}function Y0(e,t){L$(e,t);var n=Ss(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?G0(e,t.type,n):t.hasOwnProperty("defaultValue")&&G0(e,t.type,Ss(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function WS(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function G0(e,t,n){(t!=="number"||oh(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var du=Array.isArray;function bl(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o"+t.valueOf().toString()+"",t=Uf.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Ou(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var vu={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},e9=["Webkit","ms","Moz","O"];Object.keys(vu).forEach(function(e){e9.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),vu[t]=vu[e]})});function B$(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||vu.hasOwnProperty(e)&&vu[e]?(""+t).trim():t+"px"}function U$(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,o=B$(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}var t9=zt({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 q0(e,t){if(t){if(t9[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(ce(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(ce(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(ce(61))}if(t.style!=null&&typeof t.style!="object")throw Error(ce(62))}}function Q0(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){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 J0=null;function uw(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ey=null,_l=null,Sl=null;function YS(e){if(e=Ed(e)){if(typeof ey!="function")throw Error(ce(280));var t=e.stateNode;t&&(t=hm(t),ey(e.stateNode,e.type,t))}}function V$(e){_l?Sl?Sl.push(e):Sl=[e]:_l=e}function W$(){if(_l){var e=_l,t=Sl;if(Sl=_l=null,YS(e),t)for(e=0;e>>=0,e===0?32:31-(f9(e)/p9|0)|0}var Vf=64,Wf=4194304;function fu(e){switch(e&-e){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 e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function lh(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,o=e.suspendedLanes,i=e.pingedLanes,s=n&268435455;if(s!==0){var l=s&~o;l!==0?r=fu(l):(i&=s,i!==0&&(r=fu(i)))}else s=n&~o,s!==0?r=fu(s):i!==0&&(r=fu(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&o)&&(o=r&-r,i=t&-t,o>=i||o===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function _d(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-go(t),e[t]=n}function v9(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=wu),nE=" ",rE=!1;function uk(e,t){switch(e){case"keyup":return H9.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function dk(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var cl=!1;function Y9(e,t){switch(e){case"compositionend":return dk(t);case"keypress":return t.which!==32?null:(rE=!0,nE);case"textInput":return e=t.data,e===nE&&rE?null:e;default:return null}}function G9(e,t){if(cl)return e==="compositionend"||!yw&&uk(e,t)?(e=lk(),$p=mw=rs=null,cl=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=aE(n)}}function mk(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?mk(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function gk(){for(var e=window,t=oh();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=oh(e.document)}return t}function ww(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function rI(e){var t=gk(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&mk(n.ownerDocument.documentElement,n)){if(r!==null&&ww(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=r.end===void 0?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=lE(n,i);var s=lE(n,r);o&&s&&(e.rangeCount!==1||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==s.node||e.focusOffset!==s.offset)&&(t=t.createRange(),t.setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(s.node,s.offset)):(t.setEnd(s.node,s.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ul=null,sy=null,bu=null,ay=!1;function cE(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ay||ul==null||ul!==oh(r)||(r=ul,"selectionStart"in r&&ww(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}),bu&&Fu(bu,r)||(bu=r,r=dh(sy,"onSelect"),0pl||(e.current=py[pl],py[pl]=null,pl--)}function $t(e,t){pl++,py[pl]=e.current,e.current=t}var Es={},Tn=Ps(Es),Jn=Ps(!1),ba=Es;function Kl(e,t){var n=e.type.contextTypes;if(!n)return Es;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o={},i;for(i in n)o[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=o),o}function er(e){return e=e.childContextTypes,e!=null}function ph(){At(Jn),At(Tn)}function gE(e,t,n){if(Tn.current!==Es)throw Error(ce(168));$t(Tn,t),$t(Jn,n)}function Ck(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var o in r)if(!(o in t))throw Error(ce(108,QD(e)||"Unknown",o));return zt({},n,r)}function hh(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||Es,ba=Tn.current,$t(Tn,e),$t(Jn,Jn.current),!0}function vE(e,t,n){var r=e.stateNode;if(!r)throw Error(ce(169));n?(e=Ck(e,t,ba),r.__reactInternalMemoizedMergedChildContext=e,At(Jn),At(Tn),$t(Tn,e)):At(Jn),$t(Jn,n)}var li=null,mm=!1,Qv=!1;function $k(e){li===null?li=[e]:li.push(e)}function mI(e){mm=!0,$k(e)}function As(){if(!Qv&&li!==null){Qv=!0;var e=0,t=xt;try{var n=li;for(xt=1;e>=s,o-=s,ci=1<<32-go(t)+o|n<O?(F=A,A=null):F=A.sibling;var V=g(S,A,E[O],k);if(V===null){A===null&&(A=F);break}e&&A&&V.alternate===null&&t(S,A),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V,A=F}if(O===E.length)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;OO?(F=A,A=null):F=A.sibling;var J=g(S,A,V.value,k);if(J===null){A===null&&(A=F);break}e&&A&&J.alternate===null&&t(S,A),b=i(J,b,O),M===null?P=J:M.sibling=J,M=J,A=F}if(V.done)return n(S,A),Dt&&qs(S,O),P;if(A===null){for(;!V.done;O++,V=E.next())V=m(S,V.value,k),V!==null&&(b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return Dt&&qs(S,O),P}for(A=r(S,A);!V.done;O++,V=E.next())V=y(A,S,O,V.value,k),V!==null&&(e&&V.alternate!==null&&A.delete(V.key===null?O:V.key),b=i(V,b,O),M===null?P=V:M.sibling=V,M=V);return e&&A.forEach(function(G){return t(S,G)}),Dt&&qs(S,O),P}function C(S,b,E,k){if(typeof E=="object"&&E!==null&&E.type===ll&&E.key===null&&(E=E.props.children),typeof E=="object"&&E!==null){switch(E.$$typeof){case zf:e:{for(var P=E.key,M=b;M!==null;){if(M.key===P){if(P=E.type,P===ll){if(M.tag===7){n(S,M.sibling),b=o(M,E.props.children),b.return=S,S=b;break e}}else if(M.elementType===P||typeof P=="object"&&P!==null&&P.$$typeof===Ki&&EE(P)===M.type){n(S,M.sibling),b=o(M,E.props),b.ref=Jc(S,M,E),b.return=S,S=b;break e}n(S,M);break}else t(S,M);M=M.sibling}E.type===ll?(b=xa(E.props.children,S.mode,k,E.key),b.return=S,S=b):(k=Np(E.type,E.key,E.props,null,S.mode,k),k.ref=Jc(S,b,E),k.return=S,S=k)}return s(S);case al:e:{for(M=E.key;b!==null;){if(b.key===M)if(b.tag===4&&b.stateNode.containerInfo===E.containerInfo&&b.stateNode.implementation===E.implementation){n(S,b.sibling),b=o(b,E.children||[]),b.return=S,S=b;break e}else{n(S,b);break}else t(S,b);b=b.sibling}b=s0(E,S.mode,k),b.return=S,S=b}return s(S);case Ki:return M=E._init,C(S,b,M(E._payload),k)}if(du(E))return x(S,b,E,k);if(Gc(E))return _(S,b,E,k);qf(S,E)}return typeof E=="string"&&E!==""||typeof E=="number"?(E=""+E,b!==null&&b.tag===6?(n(S,b.sibling),b=o(b,E),b.return=S,S=b):(n(S,b),b=i0(E,S.mode,k),b.return=S,S=b),s(S)):n(S,b)}return C}var Gl=Nk(!0),Dk=Nk(!1),Cd={},zo=Ps(Cd),Uu=Ps(Cd),Vu=Ps(Cd);function oa(e){if(e===Cd)throw Error(ce(174));return e}function Rw(e,t){switch($t(Vu,t),$t(Uu,e),$t(zo,Cd),e=t.nodeType,e){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:Z0(null,"");break;default:e=e===8?t.parentNode:t,t=e.namespaceURI||null,e=e.tagName,t=Z0(t,e)}At(zo),$t(zo,t)}function Xl(){At(zo),At(Uu),At(Vu)}function Ik(e){oa(Vu.current);var t=oa(zo.current),n=Z0(t,e.type);t!==n&&($t(Uu,e),$t(zo,n))}function Tw(e){Uu.current===e&&(At(zo),At(Uu))}var Lt=Ps(0);function xh(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return t}else if(t.tag===19&&t.memoizedProps.revealOrder!==void 0){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var Jv=[];function Pw(){for(var e=0;en?n:4,e(!0);var r=e0.transition;e0.transition={};try{e(!1),t()}finally{xt=n,e0.transition=r}}function Qk(){return Gr().memoizedState}function wI(e,t,n){var r=ys(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Jk(e))eR(t,n);else if(n=Pk(e,t,n,r),n!==null){var o=jn();vo(n,e,r,o),tR(n,t,r)}}function xI(e,t,n){var r=ys(e),o={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Jk(e))eR(t,o);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var s=t.lastRenderedState,l=i(s,n);if(o.hasEagerState=!0,o.eagerState=l,wo(l,s)){var u=t.interleaved;u===null?(o.next=o,$w(t)):(o.next=u.next,u.next=o),t.interleaved=o;return}}catch{}finally{}n=Pk(e,t,o,r),n!==null&&(o=jn(),vo(n,e,r,o),tR(n,t,r))}}function Jk(e){var t=e.alternate;return e===jt||t!==null&&t===jt}function eR(e,t){_u=bh=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function tR(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,fw(e,n)}}var _h={readContext:Yr,useCallback:Cn,useContext:Cn,useEffect:Cn,useImperativeHandle:Cn,useInsertionEffect:Cn,useLayoutEffect:Cn,useMemo:Cn,useReducer:Cn,useRef:Cn,useState:Cn,useDebugValue:Cn,useDeferredValue:Cn,useTransition:Cn,useMutableSource:Cn,useSyncExternalStore:Cn,useId:Cn,unstable_isNewReconciler:!1},bI={readContext:Yr,useCallback:function(e,t){return ko().memoizedState=[e,t===void 0?null:t],e},useContext:Yr,useEffect:$E,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Pp(4194308,4,Yk.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Pp(4194308,4,e,t)},useInsertionEffect:function(e,t){return Pp(4,2,e,t)},useMemo:function(e,t){var n=ko();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=ko();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=wI.bind(null,jt,e),[r.memoizedState,e]},useRef:function(e){var t=ko();return e={current:e},t.memoizedState=e},useState:CE,useDebugValue:Dw,useDeferredValue:function(e){return ko().memoizedState=e},useTransition:function(){var e=CE(!1),t=e[0];return e=yI.bind(null,e[1]),ko().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=jt,o=ko();if(Dt){if(n===void 0)throw Error(ce(407));n=n()}else{if(n=t(),dn===null)throw Error(ce(349));Sa&30||jk(r,t,n)}o.memoizedState=n;var i={value:n,getSnapshot:t};return o.queue=i,$E(Bk.bind(null,r,i,e),[e]),r.flags|=2048,Ku(9,zk.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=ko(),t=dn.identifierPrefix;if(Dt){var n=ui,r=ci;n=(r&~(1<<32-go(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Wu++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=s.createElement(n,{is:r.is}):(e=s.createElement(n),n==="select"&&(s=e,r.multiple?s.multiple=!0:r.size&&(s.size=r.size))):e=s.createElementNS(e,n),e[Oo]=t,e[Bu]=r,uR(e,t,!1,!1),t.stateNode=e;e:{switch(s=Q0(n,r),n){case"dialog":Tt("cancel",e),Tt("close",e),o=r;break;case"iframe":case"object":case"embed":Tt("load",e),o=r;break;case"video":case"audio":for(o=0;oql&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304)}else{if(!r)if(e=xh(s),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),eu(i,!0),i.tail===null&&i.tailMode==="hidden"&&!s.alternate&&!Dt)return $n(t),null}else 2*Xt()-i.renderingStartTime>ql&&n!==1073741824&&(t.flags|=128,r=!0,eu(i,!1),t.lanes=4194304);i.isBackwards?(s.sibling=t.child,t.child=s):(n=i.last,n!==null?n.sibling=s:t.child=s,i.last=s)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Xt(),t.sibling=null,n=Lt.current,$t(Lt,r?n&1|2:n&1),t):($n(t),null);case 22:case 23:return Bw(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?fr&1073741824&&($n(t),t.subtreeFlags&6&&(t.flags|=8192)):$n(t),null;case 24:return null;case 25:return null}throw Error(ce(156,t.tag))}function TI(e,t){switch(bw(t),t.tag){case 1:return er(t.type)&&ph(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Xl(),At(Jn),At(Tn),Pw(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Tw(t),null;case 13:if(At(Lt),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(ce(340));Yl()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return At(Lt),null;case 4:return Xl(),null;case 10:return Cw(t.type._context),null;case 22:case 23:return Bw(),null;case 24:return null;default:return null}}var Jf=!1,Rn=!1,PI=typeof WeakSet=="function"?WeakSet:Set,Se=null;function vl(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Wt(e,t,r)}else n.current=null}function Cy(e,t,n){try{n()}catch(r){Wt(e,t,r)}}var DE=!1;function AI(e,t){if(ly=ch,e=gk(),ww(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.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,l=-1,u=-1,d=0,h=0,m=e,g=null;t:for(;;){for(var y;m!==n||o!==0&&m.nodeType!==3||(l=s+o),m!==i||r!==0&&m.nodeType!==3||(u=s+r),m.nodeType===3&&(s+=m.nodeValue.length),(y=m.firstChild)!==null;)g=m,m=y;for(;;){if(m===e)break t;if(g===n&&++d===o&&(l=s),g===i&&++h===r&&(u=s),(y=m.nextSibling)!==null)break;m=g,g=m.parentNode}m=y}n=l===-1||u===-1?null:{start:l,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(cy={focusedElem:e,selectionRange:n},ch=!1,Se=t;Se!==null;)if(t=Se,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,Se=e;else for(;Se!==null;){t=Se;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var _=x.memoizedProps,C=x.memoizedState,S=t.stateNode,b=S.getSnapshotBeforeUpdate(t.elementType===t.type?_:io(t.type,_),C);S.__reactInternalSnapshotBeforeUpdate=b}break;case 3:var E=t.stateNode.containerInfo;E.nodeType===1?E.textContent="":E.nodeType===9&&E.documentElement&&E.removeChild(E.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(ce(163))}}catch(k){Wt(t,t.return,k)}if(e=t.sibling,e!==null){e.return=t.return,Se=e;break}Se=t.return}return x=DE,DE=!1,x}function Su(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var o=r=r.next;do{if((o.tag&e)===e){var i=o.destroy;o.destroy=void 0,i!==void 0&&Cy(t,n,i)}o=o.next}while(o!==r)}}function ym(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function $y(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function pR(e){var t=e.alternate;t!==null&&(e.alternate=null,pR(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[Oo],delete t[Bu],delete t[fy],delete t[pI],delete t[hI])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function hR(e){return e.tag===5||e.tag===3||e.tag===4}function IE(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||hR(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function ky(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=fh));else if(r!==4&&(e=e.child,e!==null))for(ky(e,t,n),e=e.sibling;e!==null;)ky(e,t,n),e=e.sibling}function Ry(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ry(e,t,n),e=e.sibling;e!==null;)Ry(e,t,n),e=e.sibling}var mn=null,lo=!1;function ji(e,t,n){for(n=n.child;n!==null;)mR(e,t,n),n=n.sibling}function mR(e,t,n){if(jo&&typeof jo.onCommitFiberUnmount=="function")try{jo.onCommitFiberUnmount(um,n)}catch{}switch(n.tag){case 5:Rn||vl(n,t);case 6:var r=mn,o=lo;mn=null,ji(e,t,n),mn=r,lo=o,mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):mn.removeChild(n.stateNode));break;case 18:mn!==null&&(lo?(e=mn,n=n.stateNode,e.nodeType===8?qv(e.parentNode,n):e.nodeType===1&&qv(e,n),Iu(e)):qv(mn,n.stateNode));break;case 4:r=mn,o=lo,mn=n.stateNode.containerInfo,lo=!0,ji(e,t,n),mn=r,lo=o;break;case 0:case 11:case 14:case 15:if(!Rn&&(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||i&4)&&Cy(n,t,s),o=o.next}while(o!==r)}ji(e,t,n);break;case 1:if(!Rn&&(vl(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(l){Wt(n,t,l)}ji(e,t,n);break;case 21:ji(e,t,n);break;case 22:n.mode&1?(Rn=(r=Rn)||n.memoizedState!==null,ji(e,t,n),Rn=r):ji(e,t,n);break;default:ji(e,t,n)}}function LE(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new PI),t.forEach(function(r){var o=zI.bind(null,e,r);n.has(r)||(n.add(r),r.then(o,o))})}}function ro(e,t){var n=t.deletions;if(n!==null)for(var r=0;ro&&(o=s),r&=~i}if(r=o,r=Xt()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*MI(r/1960))-r,10e?16:e,os===null)var r=!1;else{if(e=os,os=null,Ch=0,dt&6)throw Error(ce(331));var o=dt;for(dt|=4,Se=e.current;Se!==null;){var i=Se,s=i.child;if(Se.flags&16){var l=i.deletions;if(l!==null){for(var u=0;uXt()-jw?wa(e,0):Fw|=n),tr(e,t)}function SR(e,t){t===0&&(e.mode&1?(t=Wf,Wf<<=1,!(Wf&130023424)&&(Wf=4194304)):t=1);var n=jn();e=gi(e,t),e!==null&&(_d(e,t,n),tr(e,n))}function jI(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),SR(e,n)}function zI(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,o=e.memoizedState;o!==null&&(n=o.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(ce(314))}r!==null&&r.delete(t),SR(e,n)}var ER;ER=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||Jn.current)Qn=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Qn=!1,kI(e,t,n);Qn=!!(e.flags&131072)}else Qn=!1,Dt&&t.flags&1048576&&kk(t,gh,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ap(e,t),e=t.pendingProps;var o=Kl(t,Tn.current);Cl(t,n),o=Ow(null,t,r,e,o,n);var i=Mw();return t.flags|=1,typeof o=="object"&&o!==null&&typeof o.render=="function"&&o.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,er(r)?(i=!0,hh(t)):i=!1,t.memoizedState=o.state!==null&&o.state!==void 0?o.state:null,kw(t),o.updater=gm,t.stateNode=o,o._reactInternals=t,yy(t,r,e,n),t=by(null,t,r,!0,i,n)):(t.tag=0,Dt&&i&&xw(t),Dn(null,t,o,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ap(e,t),e=t.pendingProps,o=r._init,r=o(r._payload),t.type=r,o=t.tag=UI(r),e=io(r,e),o){case 0:t=xy(null,t,r,e,n);break e;case 1:t=OE(null,t,r,e,n);break e;case 11:t=PE(null,t,r,e,n);break e;case 14:t=AE(null,t,r,io(r.type,e),n);break e}throw Error(ce(306,r,""))}return t;case 0:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),xy(e,t,r,o,n);case 1:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),OE(e,t,r,o,n);case 3:e:{if(aR(t),e===null)throw Error(ce(387));r=t.pendingProps,i=t.memoizedState,o=i.element,Ak(e,t),wh(t,r,null,n);var s=t.memoizedState;if(r=s.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:s.cache,pendingSuspenseBoundaries:s.pendingSuspenseBoundaries,transitions:s.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){o=Zl(Error(ce(423)),t),t=ME(e,t,r,n,o);break e}else if(r!==o){o=Zl(Error(ce(424)),t),t=ME(e,t,r,n,o);break e}else for(mr=ms(t.stateNode.containerInfo.firstChild),gr=t,Dt=!0,po=null,n=Dk(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Yl(),r===o){t=vi(e,t,n);break e}Dn(e,t,r,n)}t=t.child}return t;case 5:return Ik(t),e===null&&my(t),r=t.type,o=t.pendingProps,i=e!==null?e.memoizedProps:null,s=o.children,uy(r,o)?s=null:i!==null&&uy(r,i)&&(t.flags|=32),sR(e,t),Dn(e,t,s,n),t.child;case 6:return e===null&&my(t),null;case 13:return lR(e,t,n);case 4:return Rw(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Gl(t,null,r,n):Dn(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),PE(e,t,r,o,n);case 7:return Dn(e,t,t.pendingProps,n),t.child;case 8:return Dn(e,t,t.pendingProps.children,n),t.child;case 12:return Dn(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,i=t.memoizedProps,s=o.value,$t(vh,r._currentValue),r._currentValue=s,i!==null)if(wo(i.value,s)){if(i.children===o.children&&!Jn.current){t=vi(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var l=i.dependencies;if(l!==null){s=i.child;for(var u=l.firstContext;u!==null;){if(u.context===r){if(i.tag===1){u=fi(-1,n&-n),u.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var h=d.pending;h===null?u.next=u:(u.next=h.next,h.next=u),d.pending=u}}i.lanes|=n,u=i.alternate,u!==null&&(u.lanes|=n),gy(i.return,n,t),l.lanes|=n;break}u=u.next}}else if(i.tag===10)s=i.type===t.type?null:i.child;else if(i.tag===18){if(s=i.return,s===null)throw Error(ce(341));s.lanes|=n,l=s.alternate,l!==null&&(l.lanes|=n),gy(s,n,t),s=i.sibling}else s=i.child;if(s!==null)s.return=i;else for(s=i;s!==null;){if(s===t){s=null;break}if(i=s.sibling,i!==null){i.return=s.return,s=i;break}s=s.return}i=s}Dn(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=t.pendingProps.children,Cl(t,n),o=Yr(o),r=r(o),t.flags|=1,Dn(e,t,r,n),t.child;case 14:return r=t.type,o=io(r,t.pendingProps),o=io(r.type,o),AE(e,t,r,o,n);case 15:return oR(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:io(r,o),Ap(e,t),t.tag=1,er(r)?(e=!0,hh(t)):e=!1,Cl(t,n),Mk(t,r,o),yy(t,r,o,n),by(null,t,r,!0,e,n);case 19:return cR(e,t,n);case 22:return iR(e,t,n)}throw Error(ce(156,t.tag))};function CR(e,t){return q$(e,t)}function BI(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,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 Ur(e,t,n,r){return new BI(e,t,n,r)}function Vw(e){return e=e.prototype,!(!e||!e.isReactComponent)}function UI(e){if(typeof e=="function")return Vw(e)?1:0;if(e!=null){if(e=e.$$typeof,e===lw)return 11;if(e===cw)return 14}return 2}function ws(e,t){var n=e.alternate;return n===null?(n=Ur(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Np(e,t,n,r,o,i){var s=2;if(r=e,typeof e=="function")Vw(e)&&(s=1);else if(typeof e=="string")s=5;else e:switch(e){case ll:return xa(n.children,o,i,t);case aw:s=8,o|=8;break;case U0:return e=Ur(12,n,t,o|2),e.elementType=U0,e.lanes=i,e;case V0:return e=Ur(13,n,t,o),e.elementType=V0,e.lanes=i,e;case W0:return e=Ur(19,n,t,o),e.elementType=W0,e.lanes=i,e;case N$:return xm(n,o,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case O$:s=10;break e;case M$:s=9;break e;case lw:s=11;break e;case cw:s=14;break e;case Ki:s=16,r=null;break e}throw Error(ce(130,e==null?e:typeof e,""))}return t=Ur(s,n,t,o),t.elementType=e,t.type=r,t.lanes=i,t}function xa(e,t,n,r){return e=Ur(7,e,r,t),e.lanes=n,e}function xm(e,t,n,r){return e=Ur(22,e,r,t),e.elementType=N$,e.lanes=n,e.stateNode={isHidden:!1},e}function i0(e,t,n){return e=Ur(6,e,null,t),e.lanes=n,e}function s0(e,t,n){return t=Ur(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function VI(e,t,n,r,o){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=zv(0),this.expirationTimes=zv(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=zv(0),this.identifierPrefix=r,this.onRecoverableError=o,this.mutableSourceEagerHydrationData=null}function Ww(e,t,n,r,o,i,s,l,u){return e=new VI(e,t,n,l,u),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Ur(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},kw(i),e}function WI(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(TR)}catch(e){console.error(e)}}TR(),k$.exports=br;var Os=k$.exports;const XI=lm(Os);var HE=Os;z0.createRoot=HE.createRoot,z0.hydrateRoot=HE.hydrateRoot;var $d=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Ql=typeof window>"u"||"Deno"in window;function Lr(){}function ZI(e,t){return typeof e=="function"?e(t):e}function My(e){return typeof e=="number"&&e>=0&&e!==1/0}function PR(e,t){return Math.max(e+(t||0)-Date.now(),0)}function KE(e,t){const{type:n="all",exact:r,fetchStatus:o,predicate:i,queryKey:s,stale:l}=e;if(s){if(r){if(t.queryHash!==Gw(s,t.options))return!1}else if(!Xu(t.queryKey,s))return!1}if(n!=="all"){const u=t.isActive();if(n==="active"&&!u||n==="inactive"&&u)return!1}return!(typeof l=="boolean"&&t.isStale()!==l||typeof o<"u"&&o!==t.state.fetchStatus||i&&!i(t))}function YE(e,t){const{exact:n,status:r,predicate:o,mutationKey:i}=e;if(i){if(!t.options.mutationKey)return!1;if(n){if(Gu(t.options.mutationKey)!==Gu(i))return!1}else if(!Xu(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||o&&!o(t))}function Gw(e,t){return((t==null?void 0:t.queryKeyHashFn)||Gu)(e)}function Gu(e){return JSON.stringify(e,(t,n)=>Dy(n)?Object.keys(n).sort().reduce((r,o)=>(r[o]=n[o],r),{}):n)}function Xu(e,t){return e===t?!0:typeof e!=typeof t?!1:e&&t&&typeof e=="object"&&typeof t=="object"?!Object.keys(t).some(n=>!Xu(e[n],t[n])):!1}function AR(e,t){if(e===t)return e;const n=GE(e)&&GE(t);if(n||Dy(e)&&Dy(t)){const r=n?e.length:Object.keys(e).length,o=n?t:Object.keys(t),i=o.length,s=n?[]:{};let l=0;for(let u=0;u"u")return!0;const n=t.prototype;return!(!XE(n)||!n.hasOwnProperty("isPrototypeOf"))}function XE(e){return Object.prototype.toString.call(e)==="[object Object]"}function OR(e){return new Promise(t=>{setTimeout(t,e)})}function ZE(e){OR(0).then(e)}function Iy(e,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(e,t):n.structuralSharing!==!1?AR(e,t):t}function qI(e,t,n=0){const r=[...e,t];return n&&r.length>n?r.slice(1):r}function QI(e,t,n=0){const r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ua,Zi,Pl,l$,JI=(l$=class extends $d{constructor(){super();Te(this,ua,void 0);Te(this,Zi,void 0);Te(this,Pl,void 0);ye(this,Pl,t=>{if(!Ql&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){z(this,Zi)||this.setEventListener(z(this,Pl))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,Zi))==null||t.call(this),ye(this,Zi,void 0))}setEventListener(t){var n;ye(this,Pl,t),(n=z(this,Zi))==null||n.call(this),ye(this,Zi,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){z(this,ua)!==t&&(ye(this,ua,t),this.onFocus())}onFocus(){this.listeners.forEach(t=>{t()})}isFocused(){var t;return typeof z(this,ua)=="boolean"?z(this,ua):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},ua=new WeakMap,Zi=new WeakMap,Pl=new WeakMap,l$),Rh=new JI,Al,qi,Ol,c$,eL=(c$=class extends $d{constructor(){super();Te(this,Al,!0);Te(this,qi,void 0);Te(this,Ol,void 0);ye(this,Ol,t=>{if(!Ql&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){z(this,qi)||this.setEventListener(z(this,Ol))}onUnsubscribe(){var t;this.hasListeners()||((t=z(this,qi))==null||t.call(this),ye(this,qi,void 0))}setEventListener(t){var n;ye(this,Ol,t),(n=z(this,qi))==null||n.call(this),ye(this,qi,t(this.setOnline.bind(this)))}setOnline(t){z(this,Al)!==t&&(ye(this,Al,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return z(this,Al)}},Al=new WeakMap,qi=new WeakMap,Ol=new WeakMap,c$),Th=new eL;function tL(e){return Math.min(1e3*2**e,3e4)}function Cm(e){return(e??"online")==="online"?Th.isOnline():!0}var MR=class{constructor(e){this.revert=e==null?void 0:e.revert,this.silent=e==null?void 0:e.silent}};function a0(e){return e instanceof MR}function NR(e){let t=!1,n=0,r=!1,o,i,s;const l=new Promise((C,S)=>{i=C,s=S}),u=C=>{var S;r||(y(new MR(C)),(S=e.abort)==null||S.call(e))},d=()=>{t=!0},h=()=>{t=!1},m=()=>!Rh.isFocused()||e.networkMode!=="always"&&!Th.isOnline(),g=C=>{var S;r||(r=!0,(S=e.onSuccess)==null||S.call(e,C),o==null||o(),i(C))},y=C=>{var S;r||(r=!0,(S=e.onError)==null||S.call(e,C),o==null||o(),s(C))},x=()=>new Promise(C=>{var S;o=b=>{const E=r||!m();return E&&C(b),E},(S=e.onPause)==null||S.call(e)}).then(()=>{var C;o=void 0,r||(C=e.onContinue)==null||C.call(e)}),_=()=>{if(r)return;let C;try{C=e.fn()}catch(S){C=Promise.reject(S)}Promise.resolve(C).then(g).catch(S=>{var M;if(r)return;const b=e.retry??(Ql?0:3),E=e.retryDelay??tL,k=typeof E=="function"?E(n,S):E,P=b===!0||typeof b=="number"&&n{if(m())return x()}).then(()=>{t?y(S):_()})})};return Cm(e.networkMode)?_():x().then(_),{promise:l,cancel:u,continue:()=>(o==null?void 0:o())?l:Promise.resolve(),cancelRetry:d,continueRetry:h}}function nL(){let e=[],t=0,n=h=>{h()},r=h=>{h()};const o=h=>{let m;t++;try{m=h()}finally{t--,t||l()}return m},i=h=>{t?e.push(h):ZE(()=>{n(h)})},s=h=>(...m)=>{i(()=>{h(...m)})},l=()=>{const h=e;e=[],h.length&&ZE(()=>{r(()=>{h.forEach(m=>{n(m)})})})};return{batch:o,batchCalls:s,schedule:i,setNotifyFunction:h=>{n=h},setBatchNotifyFunction:h=>{r=h}}}var gn=nL(),da,u$,DR=(u$=class{constructor(){Te(this,da,void 0)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),My(this.gcTime)&&ye(this,da,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Ql?1/0:5*60*1e3))}clearGcTimeout(){z(this,da)&&(clearTimeout(z(this,da)),ye(this,da,void 0))}},da=new WeakMap,u$),Ml,Nl,Nr,Qi,Dr,cn,ud,fa,Dl,Dp,ao,ii,d$,rL=(d$=class extends DR{constructor(t){super();Te(this,Dl);Te(this,ao);Te(this,Ml,void 0);Te(this,Nl,void 0);Te(this,Nr,void 0);Te(this,Qi,void 0);Te(this,Dr,void 0);Te(this,cn,void 0);Te(this,ud,void 0);Te(this,fa,void 0);ye(this,fa,!1),ye(this,ud,t.defaultOptions),tt(this,Dl,Dp).call(this,t.options),ye(this,cn,[]),ye(this,Nr,t.cache),this.queryKey=t.queryKey,this.queryHash=t.queryHash,ye(this,Ml,t.state||oL(this.options)),this.state=z(this,Ml),this.scheduleGc()}get meta(){return this.options.meta}optionalRemove(){!z(this,cn).length&&this.state.fetchStatus==="idle"&&z(this,Nr).remove(this)}setData(t,n){const r=Iy(this.state.data,t,this.options);return tt(this,ao,ii).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){tt(this,ao,ii).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r;const n=z(this,Qi);return(r=z(this,Dr))==null||r.cancel(t),n?n.then(Lr).catch(Lr):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(z(this,Ml))}isActive(){return z(this,cn).some(t=>t.options.enabled!==!1)}isDisabled(){return this.getObserversCount()>0&&!this.isActive()}isStale(){return this.state.isInvalidated||!this.state.dataUpdatedAt||z(this,cn).some(t=>t.getCurrentResult().isStale)}isStaleByTime(t=0){return this.state.isInvalidated||!this.state.dataUpdatedAt||!PR(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}onOnline(){var n;const t=z(this,cn).find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=z(this,Dr))==null||n.continue()}addObserver(t){z(this,cn).includes(t)||(z(this,cn).push(t),this.clearGcTimeout(),z(this,Nr).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){z(this,cn).includes(t)&&(ye(this,cn,z(this,cn).filter(n=>n!==t)),z(this,cn).length||(z(this,Dr)&&(z(this,fa)?z(this,Dr).cancel({revert:!0}):z(this,Dr).cancelRetry()),this.scheduleGc()),z(this,Nr).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return z(this,cn).length}invalidate(){this.state.isInvalidated||tt(this,ao,ii).call(this,{type:"invalidate"})}fetch(t,n){var d,h,m,g;if(this.state.fetchStatus!=="idle"){if(this.state.dataUpdatedAt&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(z(this,Qi))return(d=z(this,Dr))==null||d.continueRetry(),z(this,Qi)}if(t&&tt(this,Dl,Dp).call(this,t),!this.options.queryFn){const y=z(this,cn).find(x=>x.options.queryFn);y&&tt(this,Dl,Dp).call(this,y.options)}const r=new AbortController,o={queryKey:this.queryKey,meta:this.meta},i=y=>{Object.defineProperty(y,"signal",{enumerable:!0,get:()=>(ye(this,fa,!0),r.signal)})};i(o);const s=()=>this.options.queryFn?(ye(this,fa,!1),this.options.persister?this.options.persister(this.options.queryFn,o,this):this.options.queryFn(o)):Promise.reject(new Error(`Missing queryFn: '${this.options.queryHash}'`)),l={fetchOptions:n,options:this.options,queryKey:this.queryKey,state:this.state,fetchFn:s};i(l),(h=this.options.behavior)==null||h.onFetch(l,this),ye(this,Nl,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((m=l.fetchOptions)==null?void 0:m.meta))&&tt(this,ao,ii).call(this,{type:"fetch",meta:(g=l.fetchOptions)==null?void 0:g.meta});const u=y=>{var x,_,C,S;a0(y)&&y.silent||tt(this,ao,ii).call(this,{type:"error",error:y}),a0(y)||((_=(x=z(this,Nr).config).onError)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,this.state.data,y,this)),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1};return ye(this,Dr,NR({fn:l.fetchFn,abort:r.abort.bind(r),onSuccess:y=>{var x,_,C,S;if(typeof y>"u"){u(new Error(`${this.queryHash} data is undefined`));return}this.setData(y),(_=(x=z(this,Nr).config).onSuccess)==null||_.call(x,y,this),(S=(C=z(this,Nr).config).onSettled)==null||S.call(C,y,this.state.error,this),this.isFetchingOptimistic||this.scheduleGc(),this.isFetchingOptimistic=!1},onError:u,onFail:(y,x)=>{tt(this,ao,ii).call(this,{type:"failed",failureCount:y,error:x})},onPause:()=>{tt(this,ao,ii).call(this,{type:"pause"})},onContinue:()=>{tt(this,ao,ii).call(this,{type:"continue"})},retry:l.options.retry,retryDelay:l.options.retryDelay,networkMode:l.options.networkMode})),ye(this,Qi,z(this,Dr).promise),z(this,Qi)}},Ml=new WeakMap,Nl=new WeakMap,Nr=new WeakMap,Qi=new WeakMap,Dr=new WeakMap,cn=new WeakMap,ud=new WeakMap,fa=new WeakMap,Dl=new WeakSet,Dp=function(t){this.options={...z(this,ud),...t},this.updateGcTime(this.options.gcTime)},ao=new WeakSet,ii=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:t.meta??null,fetchStatus:Cm(this.options.networkMode)?"fetching":"paused",...!r.dataUpdatedAt&&{error:null,status:"pending"}};case"success":return{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const o=t.error;return a0(o)&&o.revert&&z(this,Nl)?{...z(this,Nl),fetchStatus:"idle"}:{...r,error:o,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:o,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gn.batch(()=>{z(this,cn).forEach(r=>{r.onQueryUpdate()}),z(this,Nr).notify({query:this,type:"updated",action:t})})},d$);function oL(e){const t=typeof e.initialData=="function"?e.initialData():e.initialData,n=typeof t<"u",r=n?typeof e.initialDataUpdatedAt=="function"?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var Ro,f$,iL=(f$=class extends $d{constructor(t={}){super();Te(this,Ro,void 0);this.config=t,ye(this,Ro,new Map)}build(t,n,r){const o=n.queryKey,i=n.queryHash??Gw(o,n);let s=this.get(i);return s||(s=new rL({cache:this,queryKey:o,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(o)}),this.add(s)),s}add(t){z(this,Ro).has(t.queryHash)||(z(this,Ro).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=z(this,Ro).get(t.queryHash);n&&(t.destroy(),n===t&&z(this,Ro).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gn.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return z(this,Ro).get(t)}getAll(){return[...z(this,Ro).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>KE(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>KE(t,r)):n}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gn.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gn.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},Ro=new WeakMap,f$),To,dd,dr,Il,Po,Wi,p$,sL=(p$=class extends DR{constructor(t){super();Te(this,Po);Te(this,To,void 0);Te(this,dd,void 0);Te(this,dr,void 0);Te(this,Il,void 0);this.mutationId=t.mutationId,ye(this,dd,t.defaultOptions),ye(this,dr,t.mutationCache),ye(this,To,[]),this.state=t.state||aL(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options={...z(this,dd),...t},this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){z(this,To).includes(t)||(z(this,To).push(t),this.clearGcTimeout(),z(this,dr).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){ye(this,To,z(this,To).filter(n=>n!==t)),this.scheduleGc(),z(this,dr).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){z(this,To).length||(this.state.status==="pending"?this.scheduleGc():z(this,dr).remove(this))}continue(){var t;return((t=z(this,Il))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A;const n=()=>(ye(this,Il,NR({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(O,F)=>{tt(this,Po,Wi).call(this,{type:"failed",failureCount:O,error:F})},onPause:()=>{tt(this,Po,Wi).call(this,{type:"pause"})},onContinue:()=>{tt(this,Po,Wi).call(this,{type:"continue"})},retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode})),z(this,Il).promise),r=this.state.status==="pending";try{if(!r){tt(this,Po,Wi).call(this,{type:"pending",variables:t}),await((i=(o=z(this,dr).config).onMutate)==null?void 0:i.call(o,t,this));const F=await((l=(s=this.options).onMutate)==null?void 0:l.call(s,t));F!==this.state.context&&tt(this,Po,Wi).call(this,{type:"pending",context:F,variables:t})}const O=await n();return await((d=(u=z(this,dr).config).onSuccess)==null?void 0:d.call(u,O,t,this.state.context,this)),await((m=(h=this.options).onSuccess)==null?void 0:m.call(h,O,t,this.state.context)),await((y=(g=z(this,dr).config).onSettled)==null?void 0:y.call(g,O,null,this.state.variables,this.state.context,this)),await((_=(x=this.options).onSettled)==null?void 0:_.call(x,O,null,t,this.state.context)),tt(this,Po,Wi).call(this,{type:"success",data:O}),O}catch(O){try{throw await((S=(C=z(this,dr).config).onError)==null?void 0:S.call(C,O,t,this.state.context,this)),await((E=(b=this.options).onError)==null?void 0:E.call(b,O,t,this.state.context)),await((P=(k=z(this,dr).config).onSettled)==null?void 0:P.call(k,void 0,O,this.state.variables,this.state.context,this)),await((A=(M=this.options).onSettled)==null?void 0:A.call(M,void 0,O,t,this.state.context)),O}finally{tt(this,Po,Wi).call(this,{type:"error",error:O})}}}},To=new WeakMap,dd=new WeakMap,dr=new WeakMap,Il=new WeakMap,Po=new WeakSet,Wi=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:!Cm(this.options.networkMode),status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gn.batch(()=>{z(this,To).forEach(r=>{r.onMutationUpdate(t)}),z(this,dr).notify({mutation:this,type:"updated",action:t})})},p$);function aL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var Ir,fd,pa,h$,lL=(h$=class extends $d{constructor(t={}){super();Te(this,Ir,void 0);Te(this,fd,void 0);Te(this,pa,void 0);this.config=t,ye(this,Ir,[]),ye(this,fd,0)}build(t,n,r){const o=new sL({mutationCache:this,mutationId:++Ff(this,fd)._,options:t.defaultMutationOptions(n),state:r});return this.add(o),o}add(t){z(this,Ir).push(t),this.notify({type:"added",mutation:t})}remove(t){ye(this,Ir,z(this,Ir).filter(n=>n!==t)),this.notify({type:"removed",mutation:t})}clear(){gn.batch(()=>{z(this,Ir).forEach(t=>{this.remove(t)})})}getAll(){return z(this,Ir)}find(t){const n={exact:!0,...t};return z(this,Ir).find(r=>YE(n,r))}findAll(t={}){return z(this,Ir).filter(n=>YE(t,n))}notify(t){gn.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){return ye(this,pa,(z(this,pa)??Promise.resolve()).then(()=>{const t=z(this,Ir).filter(n=>n.state.isPaused);return gn.batch(()=>t.reduce((n,r)=>n.then(()=>r.continue().catch(Lr)),Promise.resolve()))}).then(()=>{ye(this,pa,void 0)})),z(this,pa)}},Ir=new WeakMap,fd=new WeakMap,pa=new WeakMap,h$);function cL(e){return{onFetch:(t,n)=>{const r=async()=>{var x,_,C,S,b;const o=t.options,i=(C=(_=(x=t.fetchOptions)==null?void 0:x.meta)==null?void 0:_.fetchMore)==null?void 0:C.direction,s=((S=t.state.data)==null?void 0:S.pages)||[],l=((b=t.state.data)==null?void 0:b.pageParams)||[],u={pages:[],pageParams:[]};let d=!1;const h=E=>{Object.defineProperty(E,"signal",{enumerable:!0,get:()=>(t.signal.aborted?d=!0:t.signal.addEventListener("abort",()=>{d=!0}),t.signal)})},m=t.options.queryFn||(()=>Promise.reject(new Error(`Missing queryFn: '${t.options.queryHash}'`))),g=async(E,k,P)=>{if(d)return Promise.reject();if(k==null&&E.pages.length)return Promise.resolve(E);const M={queryKey:t.queryKey,pageParam:k,direction:P?"backward":"forward",meta:t.options.meta};h(M);const A=await m(M),{maxPages:O}=t.options,F=P?QI:qI;return{pages:F(E.pages,A,O),pageParams:F(E.pageParams,k,O)}};let y;if(i&&s.length){const E=i==="backward",k=E?uL:qE,P={pages:s,pageParams:l},M=k(o,P);y=await g(P,M,E)}else{y=await g(u,l[0]??o.initialPageParam);const E=e??s.length;for(let k=1;k{var o,i;return(i=(o=t.options).persister)==null?void 0:i.call(o,r,{queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=r}}}function qE(e,{pages:t,pageParams:n}){const r=t.length-1;return e.getNextPageParam(t[r],t,n[r],n)}function uL(e,{pages:t,pageParams:n}){var r;return(r=e.getPreviousPageParam)==null?void 0:r.call(e,t[0],t,n[0],n)}var nn,Ji,es,Ll,Fl,ts,jl,zl,m$,dL=(m$=class{constructor(e={}){Te(this,nn,void 0);Te(this,Ji,void 0);Te(this,es,void 0);Te(this,Ll,void 0);Te(this,Fl,void 0);Te(this,ts,void 0);Te(this,jl,void 0);Te(this,zl,void 0);ye(this,nn,e.queryCache||new iL),ye(this,Ji,e.mutationCache||new lL),ye(this,es,e.defaultOptions||{}),ye(this,Ll,new Map),ye(this,Fl,new Map),ye(this,ts,0)}mount(){Ff(this,ts)._++,z(this,ts)===1&&(ye(this,jl,Rh.subscribe(()=>{Rh.isFocused()&&(this.resumePausedMutations(),z(this,nn).onFocus())})),ye(this,zl,Th.subscribe(()=>{Th.isOnline()&&(this.resumePausedMutations(),z(this,nn).onOnline())})))}unmount(){var e,t;Ff(this,ts)._--,z(this,ts)===0&&((e=z(this,jl))==null||e.call(this),ye(this,jl,void 0),(t=z(this,zl))==null||t.call(this),ye(this,zl,void 0))}isFetching(e){return z(this,nn).findAll({...e,fetchStatus:"fetching"}).length}isMutating(e){return z(this,Ji).findAll({...e,status:"pending"}).length}getQueryData(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state.data}ensureQueryData(e){const t=this.getQueryData(e.queryKey);return t!==void 0?Promise.resolve(t):this.fetchQuery(e)}getQueriesData(e){return this.getQueryCache().findAll(e).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(e,t,n){const r=z(this,nn).find({queryKey:e}),o=r==null?void 0:r.state.data,i=ZI(t,o);if(typeof i>"u")return;const s=this.defaultQueryOptions({queryKey:e});return z(this,nn).build(this,s).setData(i,{...n,manual:!0})}setQueriesData(e,t,n){return gn.batch(()=>this.getQueryCache().findAll(e).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(e){var t;return(t=z(this,nn).find({queryKey:e}))==null?void 0:t.state}removeQueries(e){const t=z(this,nn);gn.batch(()=>{t.findAll(e).forEach(n=>{t.remove(n)})})}resetQueries(e,t){const n=z(this,nn),r={type:"active",...e};return gn.batch(()=>(n.findAll(e).forEach(o=>{o.reset()}),this.refetchQueries(r,t)))}cancelQueries(e={},t={}){const n={revert:!0,...t},r=gn.batch(()=>z(this,nn).findAll(e).map(o=>o.cancel(n)));return Promise.all(r).then(Lr).catch(Lr)}invalidateQueries(e={},t={}){return gn.batch(()=>{if(z(this,nn).findAll(e).forEach(r=>{r.invalidate()}),e.refetchType==="none")return Promise.resolve();const n={...e,type:e.refetchType??e.type??"active"};return this.refetchQueries(n,t)})}refetchQueries(e={},t){const n={...t,cancelRefetch:(t==null?void 0:t.cancelRefetch)??!0},r=gn.batch(()=>z(this,nn).findAll(e).filter(o=>!o.isDisabled()).map(o=>{let i=o.fetch(void 0,n);return n.throwOnError||(i=i.catch(Lr)),o.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(Lr)}fetchQuery(e){const t=this.defaultQueryOptions(e);typeof t.retry>"u"&&(t.retry=!1);const n=z(this,nn).build(this,t);return n.isStaleByTime(t.staleTime)?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Lr).catch(Lr)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Lr).catch(Lr)}resumePausedMutations(){return z(this,Ji).resumePausedMutations()}getQueryCache(){return z(this,nn)}getMutationCache(){return z(this,Ji)}getDefaultOptions(){return z(this,es)}setDefaultOptions(e){ye(this,es,e)}setQueryDefaults(e,t){z(this,Ll).set(Gu(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){const t=[...z(this,Ll).values()];let n={};return t.forEach(r=>{Xu(e,r.queryKey)&&(n={...n,...r.defaultOptions})}),n}setMutationDefaults(e,t){z(this,Fl).set(Gu(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){const t=[...z(this,Fl).values()];let n={};return t.forEach(r=>{Xu(e,r.mutationKey)&&(n={...n,...r.defaultOptions})}),n}defaultQueryOptions(e){if(e!=null&&e._defaulted)return e;const t={...z(this,es).queries,...(e==null?void 0:e.queryKey)&&this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||(t.queryHash=Gw(t.queryKey,t)),typeof t.refetchOnReconnect>"u"&&(t.refetchOnReconnect=t.networkMode!=="always"),typeof t.throwOnError>"u"&&(t.throwOnError=!!t.suspense),typeof t.networkMode>"u"&&t.persister&&(t.networkMode="offlineFirst"),t}defaultMutationOptions(e){return e!=null&&e._defaulted?e:{...z(this,es).mutations,...(e==null?void 0:e.mutationKey)&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){z(this,nn).clear(),z(this,Ji).clear()}},nn=new WeakMap,Ji=new WeakMap,es=new WeakMap,Ll=new WeakMap,Fl=new WeakMap,ts=new WeakMap,jl=new WeakMap,zl=new WeakMap,m$),Xn,Ct,Bl,kn,ha,Ul,Ao,pd,Vl,Wl,ma,ga,ns,va,ya,hu,hd,Ly,md,Fy,gd,jy,vd,zy,yd,By,wd,Uy,xd,Vy,am,IR,g$,fL=(g$=class extends $d{constructor(t,n){super();Te(this,ya);Te(this,hd);Te(this,md);Te(this,gd);Te(this,vd);Te(this,yd);Te(this,wd);Te(this,xd);Te(this,am);Te(this,Xn,void 0);Te(this,Ct,void 0);Te(this,Bl,void 0);Te(this,kn,void 0);Te(this,ha,void 0);Te(this,Ul,void 0);Te(this,Ao,void 0);Te(this,pd,void 0);Te(this,Vl,void 0);Te(this,Wl,void 0);Te(this,ma,void 0);Te(this,ga,void 0);Te(this,ns,void 0);Te(this,va,void 0);ye(this,Ct,void 0),ye(this,Bl,void 0),ye(this,kn,void 0),ye(this,va,new Set),ye(this,Xn,t),this.options=n,ye(this,Ao,null),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(z(this,Ct).addObserver(this),QE(z(this,Ct),this.options)?tt(this,ya,hu).call(this):this.updateResult(),tt(this,vd,zy).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Wy(z(this,Ct),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Wy(z(this,Ct),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,tt(this,yd,By).call(this),tt(this,wd,Uy).call(this),z(this,Ct).removeObserver(this)}setOptions(t,n){const r=this.options,o=z(this,Ct);if(this.options=z(this,Xn).defaultQueryOptions(t),Ny(r,this.options)||z(this,Xn).getQueryCache().notify({type:"observerOptionsUpdated",query:z(this,Ct),observer:this}),typeof this.options.enabled<"u"&&typeof this.options.enabled!="boolean")throw new Error("Expected enabled to be a boolean");this.options.queryKey||(this.options.queryKey=r.queryKey),tt(this,xd,Vy).call(this);const i=this.hasListeners();i&&JE(z(this,Ct),o,this.options,r)&&tt(this,ya,hu).call(this),this.updateResult(n),i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||this.options.staleTime!==r.staleTime)&&tt(this,hd,Ly).call(this);const s=tt(this,md,Fy).call(this);i&&(z(this,Ct)!==o||this.options.enabled!==r.enabled||s!==z(this,ns))&&tt(this,gd,jy).call(this,s)}getOptimisticResult(t){const n=z(this,Xn).getQueryCache().build(z(this,Xn),t),r=this.createResult(n,t);return hL(this,r)&&(ye(this,kn,r),ye(this,Ul,this.options),ye(this,ha,z(this,Ct).state)),r}getCurrentResult(){return z(this,kn)}trackResult(t){const n={};return Object.keys(t).forEach(r=>{Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:()=>(z(this,va).add(r),t[r])})}),n}getCurrentQuery(){return z(this,Ct)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=z(this,Xn).defaultQueryOptions(t),r=z(this,Xn).getQueryCache().build(z(this,Xn),n);return r.isFetchingOptimistic=!0,r.fetch().then(()=>this.createResult(r,n))}fetch(t){return tt(this,ya,hu).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),z(this,kn)))}createResult(t,n){var M;const r=z(this,Ct),o=this.options,i=z(this,kn),s=z(this,ha),l=z(this,Ul),d=t!==r?t.state:z(this,Bl),{state:h}=t;let{error:m,errorUpdatedAt:g,fetchStatus:y,status:x}=h,_=!1,C;if(n._optimisticResults){const A=this.hasListeners(),O=!A&&QE(t,n),F=A&&JE(t,r,n,o);(O||F)&&(y=Cm(t.options.networkMode)?"fetching":"paused",h.dataUpdatedAt||(x="pending")),n._optimisticResults==="isRestoring"&&(y="idle")}if(n.select&&typeof h.data<"u")if(i&&h.data===(s==null?void 0:s.data)&&n.select===z(this,pd))C=z(this,Vl);else try{ye(this,pd,n.select),C=n.select(h.data),C=Iy(i==null?void 0:i.data,C,n),ye(this,Vl,C),ye(this,Ao,null)}catch(A){ye(this,Ao,A)}else C=h.data;if(typeof n.placeholderData<"u"&&typeof C>"u"&&x==="pending"){let A;if(i!=null&&i.isPlaceholderData&&n.placeholderData===(l==null?void 0:l.placeholderData))A=i.data;else if(A=typeof n.placeholderData=="function"?n.placeholderData((M=z(this,Wl))==null?void 0:M.state.data,z(this,Wl)):n.placeholderData,n.select&&typeof A<"u")try{A=n.select(A),ye(this,Ao,null)}catch(O){ye(this,Ao,O)}typeof A<"u"&&(x="success",C=Iy(i==null?void 0:i.data,A,n),_=!0)}z(this,Ao)&&(m=z(this,Ao),C=z(this,Vl),g=Date.now(),x="error");const S=y==="fetching",b=x==="pending",E=x==="error",k=b&&S;return{status:x,fetchStatus:y,isPending:b,isSuccess:x==="success",isError:E,isInitialLoading:k,isLoading:k,data:C,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:g,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:S,isRefetching:S&&!b,isLoadingError:E&&h.dataUpdatedAt===0,isPaused:y==="paused",isPlaceholderData:_,isRefetchError:E&&h.dataUpdatedAt!==0,isStale:Xw(t,n),refetch:this.refetch}}updateResult(t){const n=z(this,kn),r=this.createResult(z(this,Ct),this.options);if(ye(this,ha,z(this,Ct).state),ye(this,Ul,this.options),z(this,ha).data!==void 0&&ye(this,Wl,z(this,Ct)),Ny(r,n))return;ye(this,kn,r);const o={},i=()=>{if(!n)return!0;const{notifyOnChangeProps:s}=this.options,l=typeof s=="function"?s():s;if(l==="all"||!l&&!z(this,va).size)return!0;const u=new Set(l??z(this,va));return this.options.throwOnError&&u.add("error"),Object.keys(z(this,kn)).some(d=>{const h=d;return z(this,kn)[h]!==n[h]&&u.has(h)})};(t==null?void 0:t.listeners)!==!1&&i()&&(o.listeners=!0),tt(this,am,IR).call(this,{...o,...t})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&tt(this,vd,zy).call(this)}},Xn=new WeakMap,Ct=new WeakMap,Bl=new WeakMap,kn=new WeakMap,ha=new WeakMap,Ul=new WeakMap,Ao=new WeakMap,pd=new WeakMap,Vl=new WeakMap,Wl=new WeakMap,ma=new WeakMap,ga=new WeakMap,ns=new WeakMap,va=new WeakMap,ya=new WeakSet,hu=function(t){tt(this,xd,Vy).call(this);let n=z(this,Ct).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(Lr)),n},hd=new WeakSet,Ly=function(){if(tt(this,yd,By).call(this),Ql||z(this,kn).isStale||!My(this.options.staleTime))return;const n=PR(z(this,kn).dataUpdatedAt,this.options.staleTime)+1;ye(this,ma,setTimeout(()=>{z(this,kn).isStale||this.updateResult()},n))},md=new WeakSet,Fy=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(z(this,Ct)):this.options.refetchInterval)??!1},gd=new WeakSet,jy=function(t){tt(this,wd,Uy).call(this),ye(this,ns,t),!(Ql||this.options.enabled===!1||!My(z(this,ns))||z(this,ns)===0)&&ye(this,ga,setInterval(()=>{(this.options.refetchIntervalInBackground||Rh.isFocused())&&tt(this,ya,hu).call(this)},z(this,ns)))},vd=new WeakSet,zy=function(){tt(this,hd,Ly).call(this),tt(this,gd,jy).call(this,tt(this,md,Fy).call(this))},yd=new WeakSet,By=function(){z(this,ma)&&(clearTimeout(z(this,ma)),ye(this,ma,void 0))},wd=new WeakSet,Uy=function(){z(this,ga)&&(clearInterval(z(this,ga)),ye(this,ga,void 0))},xd=new WeakSet,Vy=function(){const t=z(this,Xn).getQueryCache().build(z(this,Xn),this.options);if(t===z(this,Ct))return;const n=z(this,Ct);ye(this,Ct,t),ye(this,Bl,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},am=new WeakSet,IR=function(t){gn.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(z(this,kn))}),z(this,Xn).getQueryCache().notify({query:z(this,Ct),type:"observerResultsUpdated"})})},g$);function pL(e,t){return t.enabled!==!1&&!e.state.dataUpdatedAt&&!(e.state.status==="error"&&t.retryOnMount===!1)}function QE(e,t){return pL(e,t)||e.state.dataUpdatedAt>0&&Wy(e,t,t.refetchOnMount)}function Wy(e,t,n){if(t.enabled!==!1){const r=typeof n=="function"?n(e):n;return r==="always"||r!==!1&&Xw(e,t)}return!1}function JE(e,t,n,r){return n.enabled!==!1&&(e!==t||r.enabled===!1)&&(!n.suspense||e.state.status!=="error")&&Xw(e,n)}function Xw(e,t){return e.isStaleByTime(t.staleTime)}function hL(e,t){return!Ny(e.getCurrentResult(),t)}var LR=f.createContext(void 0),mL=e=>{const t=f.useContext(LR);if(e)return e;if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},gL=({client:e,children:t})=>(f.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),f.createElement(LR.Provider,{value:e},t)),FR=f.createContext(!1),vL=()=>f.useContext(FR);FR.Provider;function yL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var wL=f.createContext(yL()),xL=()=>f.useContext(wL);function bL(e,t){return typeof e=="function"?e(...t):!!e}var _L=(e,t)=>{(e.suspense||e.throwOnError)&&(t.isReset()||(e.retryOnMount=!1))},SL=e=>{f.useEffect(()=>{e.clearReset()},[e])},EL=({result:e,errorResetBoundary:t,throwOnError:n,query:r})=>e.isError&&!t.isReset()&&!e.isFetching&&bL(n,[e.error,r]),CL=e=>{e.suspense&&typeof e.staleTime!="number"&&(e.staleTime=1e3)},$L=(e,t)=>(e==null?void 0:e.suspense)&&t.isPending,kL=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function RL(e,t,n){const r=mL(n),o=vL(),i=xL(),s=r.defaultQueryOptions(e);s._optimisticResults=o?"isRestoring":"optimistic",CL(s),_L(s,i),SL(i);const[l]=f.useState(()=>new t(r,s)),u=l.getOptimisticResult(s);if(f.useSyncExternalStore(f.useCallback(d=>{const h=o?()=>{}:l.subscribe(gn.batchCalls(d));return l.updateResult(),h},[l,o]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),f.useEffect(()=>{l.setOptions(s,{listeners:!1})},[s,l]),$L(s,u))throw l.setOptions(s,{listeners:!1}),kL(s,l,i);if(EL({result:u,errorResetBoundary:i,throwOnError:s.throwOnError,query:l.getCurrentQuery()}))throw u.error;return s.notifyOnChangeProps?u:l.trackResult(u)}function TL(e,t){return RL(e,fL,t)}var jR=(e=>(e.RemoveBG="RemoveBG",e.AnimeSeg="AnimeSeg",e.RealESRGAN="RealESRGAN",e.GFPGAN="GFPGAN",e.RestoreFormer="RestoreFormer",e.InteractiveSeg="InteractiveSeg",e))(jR||{}),xs=(e=>(e.NAME="name",e.CTIME="ctime",e.MTIME="mtime",e))(xs||{}),$u=(e=>(e.DESCENDING="desc",e.ASCENDING="asc",e))($u||{}),Zw=(e=>(e.ddim="ddim",e.plms="plms",e))(Zw||{}),qw=(e=>(e.INPAINT_NS="INPAINT_NS",e.INPAINT_TELEA="INPAINT_TELEA",e))(qw||{}),In=(e=>(e.x="x",e.y="y",e.xy="xy",e))(In||{}),kl=(e=>(e.text_guided="text-guided",e.shape_guided="shape-guided",e.object_remove="object-remove",e.outpainting="outpainting",e))(kl||{});function zR(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e))for(t=0;tl(i)))==null?void 0:s.classGroupId}const eC=/^\[(.+)\]$/;function AL(e){if(eC.test(e)){const t=eC.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}}function OL(e){const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return NL(Object.entries(e.classGroups),n).forEach(([i,s])=>{Hy(s,r,i,t)}),r}function Hy(e,t,n,r){e.forEach(o=>{if(typeof o=="string"){const i=o===""?t:tC(t,o);i.classGroupId=n;return}if(typeof o=="function"){if(ML(o)){Hy(o(r),t,n,r);return}t.validators.push({validator:o,classGroupId:n});return}Object.entries(o).forEach(([i,s])=>{Hy(s,tC(t,i),n,r)})})}function tC(e,t){let n=e;return t.split(Qw).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n}function ML(e){return e.isThemeGetter}function NL(e,t){return t?e.map(([n,r])=>{const o=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([s,l])=>[t+s,l])):i);return[n,o]}):e}function DL(e){if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;function o(i,s){n.set(i,s),t++,t>e&&(t=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)}}}const VR="!";function IL(e){const t=e.separator,n=t.length===1,r=t[0],o=t.length;return function(s){const l=[];let u=0,d=0,h;for(let _=0;_d?h-d:void 0;return{modifiers:l,hasImportantModifier:g,baseClassName:y,maybePostfixModifierPosition:x}}}function LL(e){if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t}function FL(e){return{cache:DL(e.cacheSize),splitModifiers:IL(e),...PL(e)}}const jL=/\s+/;function zL(e,t){const{splitModifiers:n,getClassGroupId:r,getConflictingClassGroupIds:o}=t,i=new Set;return e.trim().split(jL).map(s=>{const{modifiers:l,hasImportantModifier:u,baseClassName:d,maybePostfixModifierPosition:h}=n(s);let m=r(h?d.substring(0,h):d),g=!!h;if(!m){if(!h)return{isTailwindClass:!1,originalClassName:s};if(m=r(d),!m)return{isTailwindClass:!1,originalClassName:s};g=!1}const y=LL(l).join(":");return{isTailwindClass:!0,modifierId:u?y+VR:y,classGroupId:m,originalClassName:s,hasPostfixModifier:g}}).reverse().filter(s=>{if(!s.isTailwindClass)return!0;const{modifierId:l,classGroupId:u,hasPostfixModifier:d}=s,h=l+u;return i.has(h)?!1:(i.add(h),o(u,d).forEach(m=>i.add(l+m)),!0)}).reverse().map(s=>s.originalClassName).join(" ")}function BL(){let e=0,t,n,r="";for(;em(h),e());return n=FL(d),r=n.cache.get,o=n.cache.set,i=l,l(u)}function l(u){const d=r(u);if(d)return d;const h=zL(u,n);return o(u,h),h}return function(){return i(BL.apply(null,arguments))}}function Rt(e){const t=n=>n[e]||[];return t.isThemeGetter=!0,t}const HR=/^\[(?:([a-z-]+):)?(.+)\]$/i,VL=/^\d+\/\d+$/,WL=new Set(["px","full","screen"]),HL=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,KL=/\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$/,YL=/^-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,GL=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/;function oo(e){return ia(e)||WL.has(e)||VL.test(e)}function zi(e){return mc(e,"length",nF)}function ia(e){return!!e&&!Number.isNaN(Number(e))}function np(e){return mc(e,"number",ia)}function nu(e){return!!e&&Number.isInteger(Number(e))}function XL(e){return e.endsWith("%")&&ia(e.slice(0,-1))}function Je(e){return HR.test(e)}function Bi(e){return HL.test(e)}const ZL=new Set(["length","size","percentage"]);function qL(e){return mc(e,ZL,KR)}function QL(e){return mc(e,"position",KR)}const JL=new Set(["image","url"]);function eF(e){return mc(e,JL,oF)}function tF(e){return mc(e,"",rF)}function ru(){return!0}function mc(e,t,n){const r=HR.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1}function nF(e){return KL.test(e)}function KR(){return!1}function rF(e){return YL.test(e)}function oF(e){return GL.test(e)}function iF(){const e=Rt("colors"),t=Rt("spacing"),n=Rt("blur"),r=Rt("brightness"),o=Rt("borderColor"),i=Rt("borderRadius"),s=Rt("borderSpacing"),l=Rt("borderWidth"),u=Rt("contrast"),d=Rt("grayscale"),h=Rt("hueRotate"),m=Rt("invert"),g=Rt("gap"),y=Rt("gradientColorStops"),x=Rt("gradientColorStopPositions"),_=Rt("inset"),C=Rt("margin"),S=Rt("opacity"),b=Rt("padding"),E=Rt("saturate"),k=Rt("scale"),P=Rt("sepia"),M=Rt("skew"),A=Rt("space"),O=Rt("translate"),F=()=>["auto","contain","none"],V=()=>["auto","hidden","clip","visible","scroll"],J=()=>["auto",Je,t],G=()=>[Je,t],ae=()=>["",oo,zi],U=()=>["auto",ia,Je],te=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],L=()=>["solid","dashed","dotted","double","none"],ie=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity","plus-lighter"],K=()=>["start","end","center","between","around","evenly","stretch"],Q=()=>["","0",Je],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[ia,np],ge=()=>[ia,Je];return{cacheSize:500,separator:":",theme:{colors:[ru],spacing:[oo,zi],blur:["none","",Bi,Je],brightness:le(),borderColor:[e],borderRadius:["none","","full",Bi,Je],borderSpacing:G(),borderWidth:ae(),contrast:le(),grayscale:Q(),hueRotate:ge(),invert:Q(),gap:G(),gradientColorStops:[e],gradientColorStopPositions:[XL,zi],inset:J(),margin:J(),opacity:le(),padding:G(),saturate:le(),scale:le(),sepia:Q(),skew:ge(),space:G(),translate:G()},classGroups:{aspect:[{aspect:["auto","square","video",Je]}],container:["container"],columns:[{columns:[Bi]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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"]}],clear:[{clear:["left","right","both","none"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...te(),Je]}],overflow:[{overflow:V()}],"overflow-x":[{"overflow-x":V()}],"overflow-y":[{"overflow-y":V()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",nu,Je]}],basis:[{basis:J()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Je]}],grow:[{grow:Q()}],shrink:[{shrink:Q()}],order:[{order:["first","last","none",nu,Je]}],"grid-cols":[{"grid-cols":[ru]}],"col-start-end":[{col:["auto",{span:["full",nu,Je]},Je]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[ru]}],"row-start-end":[{row:["auto",{span:[nu,Je]},Je]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Je]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Je]}],gap:[{gap:[g]}],"gap-x":[{"gap-x":[g]}],"gap-y":[{"gap-y":[g]}],"justify-content":[{justify:["normal",...K()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...K(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...K(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],m:[{m:[C]}],mx:[{mx:[C]}],my:[{my:[C]}],ms:[{ms:[C]}],me:[{me:[C]}],mt:[{mt:[C]}],mr:[{mr:[C]}],mb:[{mb:[C]}],ml:[{ml:[C]}],"space-x":[{"space-x":[A]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[A]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit",Je,t]}],"min-w":[{"min-w":["min","max","fit",Je,oo]}],"max-w":[{"max-w":["0","none","full","min","max","fit","prose",{screen:[Bi]},Bi,Je]}],h:[{h:[Je,t,"auto","min","max","fit"]}],"min-h":[{"min-h":["min","max","fit",oo,Je]}],"max-h":[{"max-h":[Je,t,"min","max","fit"]}],"font-size":[{text:["base",Bi,zi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",np]}],"font-family":[{font:[ru]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Je]}],"line-clamp":[{"line-clamp":["none",ia,np]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",oo,Je]}],"list-image":[{"list-image":["none",Je]}],"list-style-type":[{list:["none","disc","decimal",Je]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[S]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[S]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...L(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",oo,zi]}],"underline-offset":[{"underline-offset":["auto",oo,Je]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Je]}],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",Je]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[S]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...te(),QL]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",qL]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},eF]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[x]}],"gradient-via-pos":[{via:[x]}],"gradient-to-pos":[{to:[x]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[S]}],"border-style":[{border:[...L(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[S]}],"divide-style":[{divide:L()}],"border-color":[{border:[o]}],"border-color-x":[{"border-x":[o]}],"border-color-y":[{"border-y":[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:["",...L()]}],"outline-offset":[{"outline-offset":[oo,Je]}],"outline-w":[{outline:[oo,zi]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:ae()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[S]}],"ring-offset-w":[{"ring-offset":[oo,zi]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Bi,tF]}],"shadow-color":[{shadow:[ru]}],opacity:[{opacity:[S]}],"mix-blend":[{"mix-blend":ie()}],"bg-blend":[{"bg-blend":ie()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[u]}],"drop-shadow":[{"drop-shadow":["","none",Bi,Je]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[h]}],invert:[{invert:[m]}],saturate:[{saturate:[E]}],sepia:[{sepia:[P]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[u]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[h]}],"backdrop-invert":[{"backdrop-invert":[m]}],"backdrop-opacity":[{"backdrop-opacity":[S]}],"backdrop-saturate":[{"backdrop-saturate":[E]}],"backdrop-sepia":[{"backdrop-sepia":[P]}],"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",Je]}],duration:[{duration:ge()}],ease:[{ease:["linear","in","out","in-out",Je]}],delay:[{delay:ge()}],animate:[{animate:["none","spin","ping","pulse","bounce",Je]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[k]}],"scale-x":[{"scale-x":[k]}],"scale-y":[{"scale-y":[k]}],rotate:[{rotate:[nu,Je]}],"translate-x":[{"translate-x":[O]}],"translate-y":[{"translate-y":[O]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Je]}],accent:[{accent:["auto",e]}],appearance:["appearance-none"],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",Je]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"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",Je]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[oo,zi,np]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"]},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"],"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"],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-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"]}}}const Jw=UL(iF),sF=40,is="inpaint",rp="diffusers_sd",nC="diffusers_sdxl",op="diffusers_sd_inpaint",rC="diffusers_sdxl_inpaint",l0="diffusers_other",Ky="#ffcc00bb",oC="ldm",iC="cv2",YR="Fantasy-Studio/Paint-by-Example",aF="timbrooks/instruct-pix2pix",lF="Sanster/PowerPaint-V1-stable-diffusion-inpainting",cF="Sanster/AnyText",uF="out of frame, lowres, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, disfigured, gross proportions, malformed limbs, watermark, signature";function Ce(...e){return Jw(BR(e))}function dF(){async function e(r=""){return(await fetch(r,{method:"GET",cache:"no-cache"})).json()}const t=()=>{const r=document.location;e(r+"/flaskwebgui-keep-server-alive").then(i=>i)},n=3*1e3;t(),setInterval(t,n)}function sC(e){const t=e.split(",")[0].split(":")[1].split(";")[0],n=atob(e.split(",")[1]),r=[];for(let o=0;o{const o=e.src,i=e;i.onload=n,i.onerror=s=>{i.src=o,r(s)},i.src=t})}async function fF(e){const t=URL.createObjectURL(e),n=new Image;return await Ip(n,t),n}function aC(e){return new Promise((t,n)=>{const r=new Image;r.addEventListener("load",()=>{t(r)}),r.addEventListener("error",o=>{n(o)}),r.src=e.toDataURL()})}function pF(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=()=>{n("无法加载图像。")},o.src=r.result},r.onerror=()=>{n("无法读取文件。")},r.readAsDataURL(e)})}function ku(e,t,n){return fetch(e).then(function(r){return r.arrayBuffer()}).then(function(r){return new File([r],t,{type:n})})}async function hF(){try{const{state:e}=await navigator.permissions.query({name:"clipboard-write"});return e==="granted"}catch{return!1}}function mF(e,t){return new Promise((n,r)=>e.toBlob(async o=>{o?n(o):r(new Error("Expected toBlob() to be defined"))},t))}const gF=async e=>{const t=[new ClipboardItem({[e.type]:e})];await navigator.clipboard.write(t)};function lC(e){return e.nativeEvent.button===2}function cC(e){return e.nativeEvent.button===1}async function vF(e){const t=await mF(e,"image/png");try{await gF(t)}catch{console.log("Copy image failed!")}}function yF(e,t){const n=document.createElement("a");n.href=e,n.download=t,n.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0,view:window})),setTimeout(()=>{n.remove()},100)}function c0(e){const t=e.nativeEvent;return{x:t.offsetX,y:t.offsetY}}function GR(e,t,n=Ky){e.strokeStyle=n,e.lineCap="round",e.lineJoin="round",t.forEach(r=>{!(r!=null&&r.pts.length)||!r.size||(e.lineWidth=r.size,e.beginPath(),e.moveTo(r.pts[0].x,r.pts[0].y),r.pts.forEach(o=>e.lineTo(o.x,o.y)),e.stroke())})}const Lp=(e,t,n,r=[],o="white")=>{const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)throw new Error("could not retrieve mask canvas");return r.forEach(l=>{s.drawImage(l,0,0,e,t)}),n.forEach(l=>{GR(s,l,o)}),i},Ru=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=o=>{var s;const i=(s=o.target)==null?void 0:s.result;t(i)},r.onerror=o=>{n(o)},r.readAsDataURL(e)});function XR(e,t){return function(){return e.apply(t,arguments)}}const{toString:wF}=Object.prototype,{getPrototypeOf:ex}=Object,$m=(e=>t=>{const n=wF.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Go=e=>(e=e.toLowerCase(),t=>$m(t)===e),km=e=>t=>typeof t===e,{isArray:gc}=Array,Zu=km("undefined");function xF(e){return e!==null&&!Zu(e)&&e.constructor!==null&&!Zu(e.constructor)&&Kr(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const ZR=Go("ArrayBuffer");function bF(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&ZR(e.buffer),t}const _F=km("string"),Kr=km("function"),qR=km("number"),Rm=e=>e!==null&&typeof e=="object",SF=e=>e===!0||e===!1,Fp=e=>{if($m(e)!=="object")return!1;const t=ex(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},EF=Go("Date"),CF=Go("File"),$F=Go("Blob"),kF=Go("FileList"),RF=e=>Rm(e)&&Kr(e.pipe),TF=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||Kr(e.append)&&((t=$m(e))==="formdata"||t==="object"&&Kr(e.toString)&&e.toString()==="[object FormData]"))},PF=Go("URLSearchParams"),AF=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function kd(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,o;if(typeof e!="object"&&(e=[e]),gc(e))for(r=0,o=e.length;r0;)if(o=n[r],t===o.toLowerCase())return o;return null}const JR=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,eT=e=>!Zu(e)&&e!==JR;function Yy(){const{caseless:e}=eT(this)&&this||{},t={},n=(r,o)=>{const i=e&&QR(t,o)||o;Fp(t[i])&&Fp(r)?t[i]=Yy(t[i],r):Fp(r)?t[i]=Yy({},r):gc(r)?t[i]=r.slice():t[i]=r};for(let r=0,o=arguments.length;r(kd(t,(o,i)=>{n&&Kr(o)?e[i]=XR(o,n):e[i]=o},{allOwnKeys:r}),e),MF=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),NF=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},DF=(e,t,n,r)=>{let o,i,s;const l={};if(t=t||{},e==null)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)s=o[i],(!r||r(s,e,t))&&!l[s]&&(t[s]=e[s],l[s]=!0);e=n!==!1&&ex(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},IF=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},LF=e=>{if(!e)return null;if(gc(e))return e;let t=e.length;if(!qR(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},FF=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&ex(Uint8Array)),jF=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const i=o.value;t.call(e,i[0],i[1])}},zF=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},BF=Go("HTMLFormElement"),UF=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,o){return r.toUpperCase()+o}),uC=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),VF=Go("RegExp"),tT=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};kd(n,(o,i)=>{let s;(s=t(o,i,e))!==!1&&(r[i]=s||o)}),Object.defineProperties(e,r)},WF=e=>{tT(e,(t,n)=>{if(Kr(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(Kr(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},HF=(e,t)=>{const n={},r=o=>{o.forEach(i=>{n[i]=!0})};return gc(e)?r(e):r(String(e).split(t)),n},KF=()=>{},YF=(e,t)=>(e=+e,Number.isFinite(e)?e:t),u0="abcdefghijklmnopqrstuvwxyz",dC="0123456789",nT={DIGIT:dC,ALPHA:u0,ALPHA_DIGIT:u0+u0.toUpperCase()+dC},GF=(e=16,t=nT.ALPHA_DIGIT)=>{let n="";const{length:r}=t;for(;e--;)n+=t[Math.random()*r|0];return n};function XF(e){return!!(e&&Kr(e.append)&&e[Symbol.toStringTag]==="FormData"&&e[Symbol.iterator])}const ZF=e=>{const t=new Array(10),n=(r,o)=>{if(Rm(r)){if(t.indexOf(r)>=0)return;if(!("toJSON"in r)){t[o]=r;const i=gc(r)?[]:{};return kd(r,(s,l)=>{const u=n(s,o+1);!Zu(u)&&(i[l]=u)}),t[o]=void 0,i}}return r};return n(e,0)},qF=Go("AsyncFunction"),QF=e=>e&&(Rm(e)||Kr(e))&&Kr(e.then)&&Kr(e.catch),oe={isArray:gc,isArrayBuffer:ZR,isBuffer:xF,isFormData:TF,isArrayBufferView:bF,isString:_F,isNumber:qR,isBoolean:SF,isObject:Rm,isPlainObject:Fp,isUndefined:Zu,isDate:EF,isFile:CF,isBlob:$F,isRegExp:VF,isFunction:Kr,isStream:RF,isURLSearchParams:PF,isTypedArray:FF,isFileList:kF,forEach:kd,merge:Yy,extend:OF,trim:AF,stripBOM:MF,inherits:NF,toFlatObject:DF,kindOf:$m,kindOfTest:Go,endsWith:IF,toArray:LF,forEachEntry:jF,matchAll:zF,isHTMLForm:BF,hasOwnProperty:uC,hasOwnProp:uC,reduceDescriptors:tT,freezeMethods:WF,toObjectSet:HF,toCamelCase:UF,noop:KF,toFiniteNumber:YF,findKey:QR,global:JR,isContextDefined:eT,ALPHABET:nT,generateString:GF,isSpecCompliantForm:XF,toJSONObject:ZF,isAsyncFn:qF,isThenable:QF};function ut(e,t,n,r,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),o&&(this.response=o)}oe.inherits(ut,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:oe.toJSONObject(this.config),code:this.code,status:this.response&&this.response.status?this.response.status:null}}});const rT=ut.prototype,oT={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{oT[e]={value:e}});Object.defineProperties(ut,oT);Object.defineProperty(rT,"isAxiosError",{value:!0});ut.from=(e,t,n,r,o,i)=>{const s=Object.create(rT);return oe.toFlatObject(e,s,function(u){return u!==Error.prototype},l=>l!=="isAxiosError"),ut.call(s,e.message,t,n,r,o),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};const JF=null;function Gy(e){return oe.isPlainObject(e)||oe.isArray(e)}function iT(e){return oe.endsWith(e,"[]")?e.slice(0,-2):e}function fC(e,t,n){return e?e.concat(t).map(function(o,i){return o=iT(o),!n&&i?"["+o+"]":o}).join(n?".":""):t}function ej(e){return oe.isArray(e)&&!e.some(Gy)}const tj=oe.toFlatObject(oe,{},null,function(t){return/^is[A-Z]/.test(t)});function Tm(e,t,n){if(!oe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=oe.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(_,C){return!oe.isUndefined(C[_])});const r=n.metaTokens,o=n.visitor||h,i=n.dots,s=n.indexes,u=(n.Blob||typeof Blob<"u"&&Blob)&&oe.isSpecCompliantForm(t);if(!oe.isFunction(o))throw new TypeError("visitor must be a function");function d(x){if(x===null)return"";if(oe.isDate(x))return x.toISOString();if(!u&&oe.isBlob(x))throw new ut("Blob is not supported. Use a Buffer instead.");return oe.isArrayBuffer(x)||oe.isTypedArray(x)?u&&typeof Blob=="function"?new Blob([x]):Buffer.from(x):x}function h(x,_,C){let S=x;if(x&&!C&&typeof x=="object"){if(oe.endsWith(_,"{}"))_=r?_:_.slice(0,-2),x=JSON.stringify(x);else if(oe.isArray(x)&&ej(x)||(oe.isFileList(x)||oe.endsWith(_,"[]"))&&(S=oe.toArray(x)))return _=iT(_),S.forEach(function(E,k){!(oe.isUndefined(E)||E===null)&&t.append(s===!0?fC([_],k,i):s===null?_:_+"[]",d(E))}),!1}return Gy(x)?!0:(t.append(fC(C,_,i),d(x)),!1)}const m=[],g=Object.assign(tj,{defaultVisitor:h,convertValue:d,isVisitable:Gy});function y(x,_){if(!oe.isUndefined(x)){if(m.indexOf(x)!==-1)throw Error("Circular reference detected in "+_.join("."));m.push(x),oe.forEach(x,function(S,b){(!(oe.isUndefined(S)||S===null)&&o.call(t,S,oe.isString(b)?b.trim():b,_,g))===!0&&y(S,_?_.concat(b):[b])}),m.pop()}}if(!oe.isObject(e))throw new TypeError("data must be an object");return y(e),t}function pC(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function tx(e,t){this._pairs=[],e&&Tm(e,this,t)}const sT=tx.prototype;sT.append=function(t,n){this._pairs.push([t,n])};sT.toString=function(t){const n=t?function(r){return t.call(this,r,pC)}:pC;return this._pairs.map(function(o){return n(o[0])+"="+n(o[1])},"").join("&")};function nj(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function aT(e,t,n){if(!t)return e;const r=n&&n.encode||nj,o=n&&n.serialize;let i;if(o?i=o(t,n):i=oe.isURLSearchParams(t)?t.toString():new tx(t,n).toString(r),i){const s=e.indexOf("#");s!==-1&&(e=e.slice(0,s)),e+=(e.indexOf("?")===-1?"?":"&")+i}return e}class rj{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){oe.forEach(this.handlers,function(r){r!==null&&t(r)})}}const hC=rj,lT={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},oj=typeof URLSearchParams<"u"?URLSearchParams:tx,ij=typeof FormData<"u"?FormData:null,sj=typeof Blob<"u"?Blob:null,aj={isBrowser:!0,classes:{URLSearchParams:oj,FormData:ij,Blob:sj},protocols:["http","https","file","blob","url","data"]},cT=typeof window<"u"&&typeof document<"u",lj=(e=>cT&&["ReactNative","NativeScript","NS"].indexOf(e)<0)(typeof navigator<"u"&&navigator.product),cj=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uj=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:cT,hasStandardBrowserEnv:lj,hasStandardBrowserWebWorkerEnv:cj},Symbol.toStringTag,{value:"Module"})),Io={...uj,...aj};function dj(e,t){return Tm(e,new Io.classes.URLSearchParams,Object.assign({visitor:function(n,r,o,i){return Io.isNode&&oe.isBuffer(n)?(this.append(r,n.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)}},t))}function fj(e){return oe.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function pj(e){const t={},n=Object.keys(e);let r;const o=n.length;let i;for(r=0;r=n.length;return s=!s&&oe.isArray(o)?o.length:s,u?(oe.hasOwnProp(o,s)?o[s]=[o[s],r]:o[s]=r,!l):((!o[s]||!oe.isObject(o[s]))&&(o[s]=[]),t(n,r,o[s],i)&&oe.isArray(o[s])&&(o[s]=pj(o[s])),!l)}if(oe.isFormData(e)&&oe.isFunction(e.entries)){const n={};return oe.forEachEntry(e,(r,o)=>{t(fj(r),o,n,0)}),n}return null}function hj(e,t,n){if(oe.isString(e))try{return(t||JSON.parse)(e),oe.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const nx={transitional:lT,adapter:["xhr","http"],transformRequest:[function(t,n){const r=n.getContentType()||"",o=r.indexOf("application/json")>-1,i=oe.isObject(t);if(i&&oe.isHTMLForm(t)&&(t=new FormData(t)),oe.isFormData(t))return o&&o?JSON.stringify(uT(t)):t;if(oe.isArrayBuffer(t)||oe.isBuffer(t)||oe.isStream(t)||oe.isFile(t)||oe.isBlob(t))return t;if(oe.isArrayBufferView(t))return t.buffer;if(oe.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let l;if(i){if(r.indexOf("application/x-www-form-urlencoded")>-1)return dj(t,this.formSerializer).toString();if((l=oe.isFileList(t))||r.indexOf("multipart/form-data")>-1){const u=this.env&&this.env.FormData;return Tm(l?{"files[]":t}:t,u&&new u,this.formSerializer)}}return i||o?(n.setContentType("application/json",!1),hj(t)):t}],transformResponse:[function(t){const n=this.transitional||nx.transitional,r=n&&n.forcedJSONParsing,o=this.responseType==="json";if(t&&oe.isString(t)&&(r&&!this.responseType||o)){const s=!(n&&n.silentJSONParsing)&&o;try{return JSON.parse(t)}catch(l){if(s)throw l.name==="SyntaxError"?ut.from(l,ut.ERR_BAD_RESPONSE,this,null,this.response):l}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Io.classes.FormData,Blob:Io.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};oe.forEach(["delete","get","head","post","put","patch"],e=>{nx.headers[e]={}});const rx=nx,mj=oe.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),gj=e=>{const t={};let n,r,o;return e&&e.split(` +`).forEach(function(s){o=s.indexOf(":"),n=s.substring(0,o).trim().toLowerCase(),r=s.substring(o+1).trim(),!(!n||t[n]&&mj[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},mC=Symbol("internals");function ou(e){return e&&String(e).trim().toLowerCase()}function jp(e){return e===!1||e==null?e:oe.isArray(e)?e.map(jp):String(e)}function vj(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const yj=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function d0(e,t,n,r,o){if(oe.isFunction(r))return r.call(this,t,n);if(o&&(t=n),!!oe.isString(t)){if(oe.isString(r))return t.indexOf(r)!==-1;if(oe.isRegExp(r))return r.test(t)}}function wj(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function xj(e,t){const n=oe.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(o,i,s){return this[r].call(this,t,o,i,s)},configurable:!0})})}class Pm{constructor(t){t&&this.set(t)}set(t,n,r){const o=this;function i(l,u,d){const h=ou(u);if(!h)throw new Error("header name must be a non-empty string");const m=oe.findKey(o,h);(!m||o[m]===void 0||d===!0||d===void 0&&o[m]!==!1)&&(o[m||u]=jp(l))}const s=(l,u)=>oe.forEach(l,(d,h)=>i(d,h,u));return oe.isPlainObject(t)||t instanceof this.constructor?s(t,n):oe.isString(t)&&(t=t.trim())&&!yj(t)?s(gj(t),n):t!=null&&i(n,t,r),this}get(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);if(r){const o=this[r];if(!n)return o;if(n===!0)return vj(o);if(oe.isFunction(n))return n.call(this,o,r);if(oe.isRegExp(n))return n.exec(o);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=ou(t),t){const r=oe.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||d0(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let o=!1;function i(s){if(s=ou(s),s){const l=oe.findKey(r,s);l&&(!n||d0(r,r[l],l,n))&&(delete r[l],o=!0)}}return oe.isArray(t)?t.forEach(i):i(t),o}clear(t){const n=Object.keys(this);let r=n.length,o=!1;for(;r--;){const i=n[r];(!t||d0(this,this[i],i,t,!0))&&(delete this[i],o=!0)}return o}normalize(t){const n=this,r={};return oe.forEach(this,(o,i)=>{const s=oe.findKey(r,i);if(s){n[s]=jp(o),delete n[i];return}const l=t?wj(i):String(i).trim();l!==i&&delete n[i],n[l]=jp(o),r[l]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return oe.forEach(this,(r,o)=>{r!=null&&r!==!1&&(n[o]=t&&oe.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(` +`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[mC]=this[mC]={accessors:{}}).accessors,o=this.prototype;function i(s){const l=ou(s);r[l]||(xj(o,s),r[l]=!0)}return oe.isArray(t)?t.forEach(i):i(t),this}}Pm.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);oe.reduceDescriptors(Pm.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});oe.freezeMethods(Pm);const pi=Pm;function f0(e,t){const n=this||rx,r=t||n,o=pi.from(r.headers);let i=r.data;return oe.forEach(e,function(l){i=l.call(n,i,o.normalize(),t?t.status:void 0)}),o.normalize(),i}function dT(e){return!!(e&&e.__CANCEL__)}function Rd(e,t,n){ut.call(this,e??"canceled",ut.ERR_CANCELED,t,n),this.name="CanceledError"}oe.inherits(Rd,ut,{__CANCEL__:!0});function bj(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new ut("Request failed with status code "+n.status,[ut.ERR_BAD_REQUEST,ut.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}const _j=Io.hasStandardBrowserEnv?{write(e,t,n,r,o,i){const s=[e+"="+encodeURIComponent(t)];oe.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),oe.isString(r)&&s.push("path="+r),oe.isString(o)&&s.push("domain="+o),i===!0&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Sj(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Ej(e,t){return t?e.replace(/\/+$/,"")+"/"+t.replace(/^\/+/,""):e}function fT(e,t){return e&&!Sj(t)?Ej(e,t):t}const Cj=Io.hasStandardBrowserEnv?function(){const t=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");let r;function o(i){let s=i;return t&&(n.setAttribute("href",s),s=n.href),n.setAttribute("href",s),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:n.pathname.charAt(0)==="/"?n.pathname:"/"+n.pathname}}return r=o(window.location.href),function(s){const l=oe.isString(s)?o(s):s;return l.protocol===r.protocol&&l.host===r.host}}():function(){return function(){return!0}}();function $j(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function kj(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,i=0,s;return t=t!==void 0?t:1e3,function(u){const d=Date.now(),h=r[i];s||(s=d),n[o]=u,r[o]=d;let m=i,g=0;for(;m!==o;)g+=n[m++],m=m%e;if(o=(o+1)%e,o===i&&(i=(i+1)%e),d-s{const i=o.loaded,s=o.lengthComputable?o.total:void 0,l=i-n,u=r(l),d=i<=s;n=i;const h={loaded:i,total:s,progress:s?i/s:void 0,bytes:l,rate:u||void 0,estimated:u&&s&&d?(s-i)/u:void 0,event:o};h[t?"download":"upload"]=!0,e(h)}}const Rj=typeof XMLHttpRequest<"u",Tj=Rj&&function(e){return new Promise(function(n,r){let o=e.data;const i=pi.from(e.headers).normalize();let{responseType:s,withXSRFToken:l}=e,u;function d(){e.cancelToken&&e.cancelToken.unsubscribe(u),e.signal&&e.signal.removeEventListener("abort",u)}let h;if(oe.isFormData(o)){if(Io.hasStandardBrowserEnv||Io.hasStandardBrowserWebWorkerEnv)i.setContentType(!1);else if((h=i.getContentType())!==!1){const[_,...C]=h?h.split(";").map(S=>S.trim()).filter(Boolean):[];i.setContentType([_||"multipart/form-data",...C].join("; "))}}let m=new XMLHttpRequest;if(e.auth){const _=e.auth.username||"",C=e.auth.password?unescape(encodeURIComponent(e.auth.password)):"";i.set("Authorization","Basic "+btoa(_+":"+C))}const g=fT(e.baseURL,e.url);m.open(e.method.toUpperCase(),aT(g,e.params,e.paramsSerializer),!0),m.timeout=e.timeout;function y(){if(!m)return;const _=pi.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders()),S={data:!s||s==="text"||s==="json"?m.responseText:m.response,status:m.status,statusText:m.statusText,headers:_,config:e,request:m};bj(function(E){n(E),d()},function(E){r(E),d()},S),m=null}if("onloadend"in m?m.onloadend=y:m.onreadystatechange=function(){!m||m.readyState!==4||m.status===0&&!(m.responseURL&&m.responseURL.indexOf("file:")===0)||setTimeout(y)},m.onabort=function(){m&&(r(new ut("Request aborted",ut.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ut("Network Error",ut.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let C=e.timeout?"timeout of "+e.timeout+"ms exceeded":"timeout exceeded";const S=e.transitional||lT;e.timeoutErrorMessage&&(C=e.timeoutErrorMessage),r(new ut(C,S.clarifyTimeoutError?ut.ETIMEDOUT:ut.ECONNABORTED,e,m)),m=null},Io.hasStandardBrowserEnv&&(l&&oe.isFunction(l)&&(l=l(e)),l||l!==!1&&Cj(g))){const _=e.xsrfHeaderName&&e.xsrfCookieName&&_j.read(e.xsrfCookieName);_&&i.set(e.xsrfHeaderName,_)}o===void 0&&i.setContentType(null),"setRequestHeader"in m&&oe.forEach(i.toJSON(),function(C,S){m.setRequestHeader(S,C)}),oe.isUndefined(e.withCredentials)||(m.withCredentials=!!e.withCredentials),s&&s!=="json"&&(m.responseType=e.responseType),typeof e.onDownloadProgress=="function"&&m.addEventListener("progress",gC(e.onDownloadProgress,!0)),typeof e.onUploadProgress=="function"&&m.upload&&m.upload.addEventListener("progress",gC(e.onUploadProgress)),(e.cancelToken||e.signal)&&(u=_=>{m&&(r(!_||_.type?new Rd(null,e,m):_),m.abort(),m=null)},e.cancelToken&&e.cancelToken.subscribe(u),e.signal&&(e.signal.aborted?u():e.signal.addEventListener("abort",u)));const x=$j(g);if(x&&Io.protocols.indexOf(x)===-1){r(new ut("Unsupported protocol "+x+":",ut.ERR_BAD_REQUEST,e));return}m.send(o||null)})},Xy={http:JF,xhr:Tj};oe.forEach(Xy,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const vC=e=>`- ${e}`,Pj=e=>oe.isFunction(e)||e===null||e===!1,pT={getAdapter:e=>{e=oe.isArray(e)?e:[e];const{length:t}=e;let n,r;const o={};for(let i=0;i`adapter ${l} `+(u===!1?"is not supported by the environment":"is not available in the build"));let s=t?i.length>1?`since : +`+i.map(vC).join(` +`):" "+vC(i[0]):"as no adapter specified";throw new ut("There is no suitable adapter to dispatch the request "+s,"ERR_NOT_SUPPORT")}return r},adapters:Xy};function p0(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Rd(null,e)}function yC(e){return p0(e),e.headers=pi.from(e.headers),e.data=f0.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),pT.getAdapter(e.adapter||rx.adapter)(e).then(function(r){return p0(e),r.data=f0.call(e,e.transformResponse,r),r.headers=pi.from(r.headers),r},function(r){return dT(r)||(p0(e),r&&r.response&&(r.response.data=f0.call(e,e.transformResponse,r.response),r.response.headers=pi.from(r.response.headers))),Promise.reject(r)})}const wC=e=>e instanceof pi?e.toJSON():e;function Jl(e,t){t=t||{};const n={};function r(d,h,m){return oe.isPlainObject(d)&&oe.isPlainObject(h)?oe.merge.call({caseless:m},d,h):oe.isPlainObject(h)?oe.merge({},h):oe.isArray(h)?h.slice():h}function o(d,h,m){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d,m)}else return r(d,h,m)}function i(d,h){if(!oe.isUndefined(h))return r(void 0,h)}function s(d,h){if(oe.isUndefined(h)){if(!oe.isUndefined(d))return r(void 0,d)}else return r(void 0,h)}function l(d,h,m){if(m in t)return r(d,h);if(m in e)return r(void 0,d)}const u={url:i,method:i,data:i,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:l,headers:(d,h)=>o(wC(d),wC(h),!0)};return oe.forEach(Object.keys(Object.assign({},e,t)),function(h){const m=u[h]||o,g=m(e[h],t[h],h);oe.isUndefined(g)&&m!==l||(n[h]=g)}),n}const hT="1.6.2",ox={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{ox[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const xC={};ox.transitional=function(t,n,r){function o(i,s){return"[Axios v"+hT+"] Transitional option '"+i+"'"+s+(r?". "+r:"")}return(i,s,l)=>{if(t===!1)throw new ut(o(s," has been removed"+(n?" in "+n:"")),ut.ERR_DEPRECATED);return n&&!xC[s]&&(xC[s]=!0,console.warn(o(s," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(i,s,l):!0}};function Aj(e,t,n){if(typeof e!="object")throw new ut("options must be an object",ut.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const i=r[o],s=t[i];if(s){const l=e[i],u=l===void 0||s(l,i,e);if(u!==!0)throw new ut("option "+i+" must be "+u,ut.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new ut("Unknown option "+i,ut.ERR_BAD_OPTION)}}const Zy={assertOptions:Aj,validators:ox},Ui=Zy.validators;class Ph{constructor(t){this.defaults=t,this.interceptors={request:new hC,response:new hC}}request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Jl(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:i}=n;r!==void 0&&Zy.assertOptions(r,{silentJSONParsing:Ui.transitional(Ui.boolean),forcedJSONParsing:Ui.transitional(Ui.boolean),clarifyTimeoutError:Ui.transitional(Ui.boolean)},!1),o!=null&&(oe.isFunction(o)?n.paramsSerializer={serialize:o}:Zy.assertOptions(o,{encode:Ui.function,serialize:Ui.function},!0)),n.method=(n.method||this.defaults.method||"get").toLowerCase();let s=i&&oe.merge(i.common,i[n.method]);i&&oe.forEach(["delete","get","head","post","put","patch","common"],x=>{delete i[x]}),n.headers=pi.concat(s,i);const l=[];let u=!0;this.interceptors.request.forEach(function(_){typeof _.runWhen=="function"&&_.runWhen(n)===!1||(u=u&&_.synchronous,l.unshift(_.fulfilled,_.rejected))});const d=[];this.interceptors.response.forEach(function(_){d.push(_.fulfilled,_.rejected)});let h,m=0,g;if(!u){const x=[yC.bind(this),void 0];for(x.unshift.apply(x,l),x.push.apply(x,d),g=x.length,h=Promise.resolve(n);m{if(!r._listeners)return;let i=r._listeners.length;for(;i-- >0;)r._listeners[i](o);r._listeners=null}),this.promise.then=o=>{let i;const s=new Promise(l=>{r.subscribe(l),i=l}).then(o);return s.cancel=function(){r.unsubscribe(i)},s},t(function(i,s,l){r.reason||(r.reason=new Rd(i,s,l),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}static source(){let t;return{token:new ix(function(o){t=o}),cancel:t}}}const Oj=ix;function Mj(e){return function(n){return e.apply(null,n)}}function Nj(e){return oe.isObject(e)&&e.isAxiosError===!0}const qy={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(qy).forEach(([e,t])=>{qy[t]=e});const Dj=qy;function mT(e){const t=new zp(e),n=XR(zp.prototype.request,t);return oe.extend(n,zp.prototype,t,{allOwnKeys:!0}),oe.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return mT(Jl(e,o))},n}const Qt=mT(rx);Qt.Axios=zp;Qt.CanceledError=Rd;Qt.CancelToken=Oj;Qt.isCancel=dT;Qt.VERSION=hT;Qt.toFormData=Tm;Qt.AxiosError=ut;Qt.Cancel=Qt.CanceledError;Qt.all=function(t){return Promise.all(t)};Qt.spread=Mj;Qt.isAxiosError=Nj;Qt.mergeConfig=Jl;Qt.AxiosHeaders=pi;Qt.formToJSON=e=>uT(oe.isHTMLForm(e)?new FormData(e):e);Qt.getAdapter=pT.getAdapter;Qt.HttpStatusCode=Dj;Qt.default=Qt;const Ij=Qt,Ms="/api/v1",vc=Ij.create({baseURL:Ms});async function Lj(e,t,n,r,o,i=null){const s=await Ru(e),l=await Ru(o),u=i?await Ru(i):null,d=await fetch(`${Ms}/inpaint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({image:s,mask:l,ldm_steps:t.ldmSteps,ldm_sampler:t.ldmSampler,zits_wireframe:t.zitsWireframe,cv2_flag:t.cv2Flag,cv2_radius:t.cv2Radius,hd_strategy:"Crop",hd_strategy_crop_triger_size:640,hd_strategy_crop_margin:128,hd_trategy_resize_imit:2048,prompt:t.prompt,negative_prompt:t.negativePrompt,use_croper:t.showCropper,croper_x:n.x,croper_y:n.y,croper_height:n.height,croper_width:n.width,use_extender:t.showExtender,extender_x:r.x,extender_y:r.y,extender_height:r.height,extender_width:r.width,sd_mask_blur:t.sdMaskBlur,sd_strength:t.sdStrength,sd_steps:t.sdSteps,sd_guidance_scale:t.sdGuidanceScale,sd_sampler:t.sdSampler,sd_seed:t.seedFixed?t.seed:-1,sd_match_histograms:t.sdMatchHistograms,sd_freeu:t.enableFreeu,sd_freeu_config:t.freeuConfig,sd_lcm_lora:t.enableLCMLora,paint_by_example_example_image:u,p2p_image_guidance_scale:t.p2pImageGuidanceScale,enable_controlnet:t.enableControlnet,controlnet_conditioning_scale:t.controlnetConditioningScale,controlnet_method:t.controlnetMethod?t.controlnetMethod:"",powerpaint_task:t.showExtender?kl.outpainting:t.powerpaintTask})});if(d.ok){const m=await d.blob();return{blob:URL.createObjectURL(m),seed:d.headers.get("X-Seed")}}const h=await d.json();throw new Error(`Something went wrong: ${h.errors}`)}async function Fj(){return(await vc.get("/server-config")).data}async function jj(e){return(await vc.post("/model",{name:e})).data}async function zj(){return(await vc.get("/model")).data}function Bj(){return vc.get("/models").then(e=>e.data)}async function gT(e,t,n,r,o){const i=await Ru(n),l=await fetch(`${Ms}/${e?"run_plugin_gen_mask":"run_plugin_gen_image"}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:t,image:i,upscale:r,clicks:o})});if(l.ok){const d=await l.blob();return{blob:URL.createObjectURL(d)}}const u=await l.json();throw new Error(u)}async function Uj(e,t){const n=await fetch(`${Ms}/media_file?tab=${e}&filename=${encodeURIComponent(t)}`,{method:"GET"});if(n.ok){const o=await n.blob();return new File([o],t,{type:n.headers.get("Content-Type")??"image/png"})}const r=await n.json();throw new Error(r.errors)}async function Vj(e){return(await vc.get("medias",{params:{tab:e}})).data}async function Wj(e,t,n){const r=await ku(e.src,t,n),o=new FormData;o.append("file",r);try{const i=await fetch(`${Ms}/save_image`,{method:"POST",body:o});if(!i.ok){const s=await i.text();throw new Error(s)}}catch(i){throw new Error(`Something went wrong: ${i}`)}}async function Hj(e){const t=new FormData;return t.append("file",e),(await vc.post("/gen-info",t)).data}async function Kj(e,t,n){const r=await Ru(e),o=await fetch(`${Ms}/adjust_mask`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mask:r,operate:t,kernel_size:n})});if(o.ok)return await o.blob();const i=await o.json();throw new Error(i)}function Yj(){const[e,t]=f.useState(null),n=f.useCallback(()=>{const r=new Headers;r.append("pragma","no-cache"),r.append("cache-control","no-cache"),fetch(`${Ms}/inputimage`,{headers:r}).then(async o=>{var l;if(!o.ok)throw new Error("No input image found");const i=(l=o.headers.get("content-disposition"))==null?void 0:l.split("filename=")[1].split(";")[0],s=await o.blob();if(s&&s.type.startsWith("image")){const u=new File([s],i!==void 0?i:"inputImage");t(u)}}).catch(o=>{console.log(o)})},[t]);return f.useEffect(()=>{n()},[n]),e}function xo(e,t){if(e==null)return{};var n={},r=Object.keys(e),o,i;for(i=0;i=0)&&(n[o]=e[o]);return n}var Gj=["color"],Xj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Gj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Zj=["color"],vT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Zj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),qj=["color"],Qj=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,qj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),Jj=["color"],ez=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,Jj);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M6.1584 3.13508C6.35985 2.94621 6.67627 2.95642 6.86514 3.15788L10.6151 7.15788C10.7954 7.3502 10.7954 7.64949 10.6151 7.84182L6.86514 11.8418C6.67627 12.0433 6.35985 12.0535 6.1584 11.8646C5.95694 11.6757 5.94673 11.3593 6.1356 11.1579L9.565 7.49985L6.1356 3.84182C5.94673 3.64036 5.95694 3.32394 6.1584 3.13508Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),tz=["color"],nz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,tz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.13523 8.84197C3.3241 9.04343 3.64052 9.05363 3.84197 8.86477L7.5 5.43536L11.158 8.86477C11.3595 9.05363 11.6759 9.04343 11.8648 8.84197C12.0536 8.64051 12.0434 8.32409 11.842 8.13523L7.84197 4.38523C7.64964 4.20492 7.35036 4.20492 7.15803 4.38523L3.15803 8.13523C2.95657 8.32409 2.94637 8.64051 3.13523 8.84197Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),rz=["color"],yT=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,rz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),oz=["color"],iz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,oz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M9.875 7.5C9.875 8.81168 8.81168 9.875 7.5 9.875C6.18832 9.875 5.125 8.81168 5.125 7.5C5.125 6.18832 6.18832 5.125 7.5 5.125C8.81168 5.125 9.875 6.18832 9.875 7.5Z",fill:r}))}),sz=["color"],az=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,sz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M10 6.5C10 8.433 8.433 10 6.5 10C4.567 10 3 8.433 3 6.5C3 4.567 4.567 3 6.5 3C8.433 3 10 4.567 10 6.5ZM9.30884 10.0159C8.53901 10.6318 7.56251 11 6.5 11C4.01472 11 2 8.98528 2 6.5C2 4.01472 4.01472 2 6.5 2C8.98528 2 11 4.01472 11 6.5C11 7.56251 10.6318 8.53901 10.0159 9.30884L12.8536 12.1464C13.0488 12.3417 13.0488 12.6583 12.8536 12.8536C12.6583 13.0488 12.3417 13.0488 12.1464 12.8536L9.30884 10.0159Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),lz=["color"],cz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,lz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M3.24182 2.32181C3.3919 2.23132 3.5784 2.22601 3.73338 2.30781L12.7334 7.05781C12.8974 7.14436 13 7.31457 13 7.5C13 7.68543 12.8974 7.85564 12.7334 7.94219L3.73338 12.6922C3.5784 12.774 3.3919 12.7687 3.24182 12.6782C3.09175 12.5877 3 12.4252 3 12.25V2.75C3 2.57476 3.09175 2.4123 3.24182 2.32181ZM4 3.57925V11.4207L11.4288 7.5L4 3.57925Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),uz=["color"],dz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,uz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M7 2H1.5C1.22386 2 1 2.22386 1 2.5V7H7V2ZM8 2V7H14V2.5C14 2.22386 13.7761 2 13.5 2H8ZM7 8H1V12.5C1 12.7761 1.22386 13 1.5 13H7V8ZM8 13V8H14V12.5C14 12.7761 13.7761 13 13.5 13H8ZM1.5 1C0.671573 1 0 1.67157 0 2.5V12.5C0 13.3284 0.671573 14 1.5 14H13.5C14.3284 14 15 13.3284 15 12.5V2.5C15 1.67157 14.3284 1 13.5 1H1.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))}),fz=["color"],pz=f.forwardRef(function(e,t){var n=e.color,r=n===void 0?"currentColor":n,o=xo(e,fz);return f.createElement("svg",Object.assign({width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg"},o,{ref:t}),f.createElement("path",{d:"M1.5 2H13.5C13.7761 2 14 2.22386 14 2.5V7H1V2.5C1 2.22386 1.22386 2 1.5 2ZM1 8V12.5C1 12.7761 1.22386 13 1.5 13H13.5C13.7761 13 14 12.7761 14 12.5V8H1ZM0 2.5C0 1.67157 0.671573 1 1.5 1H13.5C14.3284 1 15 1.67157 15 2.5V12.5C15 13.3284 14.3284 14 13.5 14H1.5C0.671573 14 0 13.3284 0 12.5V2.5Z",fill:r,fillRule:"evenodd",clipRule:"evenodd"}))});function Y(){return Y=Object.assign?Object.assign.bind():function(e){for(var t=1;te.forEach(n=>hz(n,t))}function Be(...e){return f.useCallback(Am(...e),e)}const Wo=f.forwardRef((e,t)=>{const{children:n,...r}=e,o=f.Children.toArray(n),i=o.find(mz);if(i){const s=i.props.children,l=o.map(u=>u===i?f.Children.count(s)>1?f.Children.only(null):f.isValidElement(s)?s.props.children:null:u);return f.createElement(Qy,Y({},r,{ref:t}),f.isValidElement(s)?f.cloneElement(s,void 0,l):null)}return f.createElement(Qy,Y({},r,{ref:t}),n)});Wo.displayName="Slot";const Qy=f.forwardRef((e,t)=>{const{children:n,...r}=e;return f.isValidElement(n)?f.cloneElement(n,{...gz(r,n.props),ref:t?Am(t,n.ref):n.ref}):f.Children.count(n)>1?f.Children.only(null):null});Qy.displayName="SlotClone";const sx=({children:e})=>f.createElement(f.Fragment,null,e);function mz(e){return f.isValidElement(e)&&e.type===sx}function gz(e,t){const n={...t};for(const r in t){const o=e[r],i=t[r];/^on[A-Z]/.test(r)?o&&i?n[r]=(...l)=>{i(...l),o(...l)}:o&&(n[r]=o):r==="style"?n[r]={...o,...i}:r==="className"&&(n[r]=[o,i].filter(Boolean).join(" "))}return{...e,...n}}const bC=e=>typeof e=="boolean"?"".concat(e):e===0?"0":e,_C=BR,Om=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return _C(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:o,defaultVariants:i}=t,s=Object.keys(o).map(d=>{const h=n==null?void 0:n[d],m=i==null?void 0:i[d];if(h===null)return null;const g=bC(h)||bC(m);return o[d][g]}),l=n&&Object.entries(n).reduce((d,h)=>{let[m,g]=h;return g===void 0||(d[m]=g),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,h)=>{let{class:m,className:g,...y}=h;return Object.entries(y).every(x=>{let[_,C]=x;return Array.isArray(C)?C.includes({...i,...l}[_]):{...i,...l}[_]===C})?[...d,m,g]:d},[]);return _C(e,s,u,n==null?void 0:n.class,n==null?void 0:n.className)};var vz={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};function yz(e,t){let n;try{n=e()}catch{return}return{getItem:o=>{var i;const s=u=>u===null?null:JSON.parse(u,t==null?void 0:t.reviver),l=(i=n.getItem(o))!=null?i:null;return l instanceof Promise?l.then(s):s(l)},setItem:(o,i)=>n.setItem(o,JSON.stringify(i,t==null?void 0:t.replacer)),removeItem:o=>n.removeItem(o)}}const qu=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return qu(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return qu(r)(n)}}}},wz=(e,t)=>(n,r,o)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:C=>C,version:0,merge:(C,S)=>({...S,...C}),...t},s=!1;const l=new Set,u=new Set;let d;try{d=i.getStorage()}catch{}if(!d)return e((...C)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...C)},r,o);const h=qu(i.serialize),m=()=>{const C=i.partialize({...r()});let S;const b=h({state:C,version:i.version}).then(E=>d.setItem(i.name,E)).catch(E=>{S=E});if(S)throw S;return b},g=o.setState;o.setState=(C,S)=>{g(C,S),m()};const y=e((...C)=>{n(...C),m()},r,o);let x;const _=()=>{var C;if(!d)return;s=!1,l.forEach(b=>b(r()));const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,r()))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)return i.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return x=i.merge(b,(E=r())!=null?E:y),n(x,!0),m()}).then(()=>{S==null||S(x,void 0),s=!0,u.forEach(b=>b(x))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:C=>{i={...i,...C},C.getStorage&&(d=C.getStorage())},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>s,onHydrate:C=>(l.add(C),()=>{l.delete(C)}),onFinishHydration:C=>(u.add(C),()=>{u.delete(C)})},_(),x||y},xz=(e,t)=>(n,r,o)=>{let i={storage:yz(()=>localStorage),partialize:_=>_,version:0,merge:(_,C)=>({...C,..._}),...t},s=!1;const l=new Set,u=new Set;let d=i.storage;if(!d)return e((..._)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(..._)},r,o);const h=()=>{const _=i.partialize({...r()});return d.setItem(i.name,{state:_,version:i.version})},m=o.setState;o.setState=(_,C)=>{m(_,C),h()};const g=e((..._)=>{n(..._),h()},r,o);let y;const x=()=>{var _,C;if(!d)return;s=!1,l.forEach(b=>{var E;return b((E=r())!=null?E:g)});const S=((C=i.onRehydrateStorage)==null?void 0:C.call(i,(_=r())!=null?_:g))||void 0;return qu(d.getItem.bind(d))(i.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==i.version){if(i.migrate)return i.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var E;return y=i.merge(b,(E=r())!=null?E:g),n(y,!0),h()}).then(()=>{S==null||S(y,void 0),y=r(),s=!0,u.forEach(b=>b(y))}).catch(b=>{S==null||S(void 0,b)})};return o.persist={setOptions:_=>{i={...i,..._},_.storage&&(d=_.storage)},clearStorage:()=>{d==null||d.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>s,onHydrate:_=>(l.add(_),()=>{l.delete(_)}),onFinishHydration:_=>(u.add(_),()=>{u.delete(_)})},i.skipHydration||x(),y||g},bz=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((vz?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),wz(e,t)):xz(e,t),_z=bz;function Sz(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,o]of e)if(!Object.is(o,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r=0;r{t(n,r,e)}):e.forEach((n,r)=>t(r,n,e))}function Mm(e){const t=e[wr];return t?t.type_:Array.isArray(e)?1:Nm(e)?2:Dm(e)?3:0}function Jy(e,t){return Mm(e)===2?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function bT(e,t,n){const r=Mm(e);r===2?e.set(t,n):r===3?e.add(n):e[t]=n}function Cz(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Nm(e){return e instanceof Map}function Dm(e){return e instanceof Set}function Js(e){return e.copy_||e.base_}function e1(e,t){if(Nm(e))return new Map(e);if(Dm(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);if(!t&&xT(e))return ec(e)?{...e}:Object.assign(Object.create(null),e);const n=Object.getOwnPropertyDescriptors(e);delete n[wr];let r=Reflect.ownKeys(n);for(let o=0;o1&&(e.set=e.add=e.clear=e.delete=$z),Object.freeze(e),t&&Qu(e,(n,r)=>ax(r,!0))),e}function $z(){ho(2)}function Im(e){return Object.isFrozen(e)}var kz={};function ka(e){const t=kz[e];return t||ho(0,e),t}var Ju;function _T(){return Ju}function Rz(e,t){return{drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function EC(e,t){t&&(ka("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function t1(e){n1(e),e.drafts_.forEach(Tz),e.drafts_=null}function n1(e){e===Ju&&(Ju=e.parent_)}function CC(e){return Ju=Rz(Ju,e)}function Tz(e){const t=e[wr];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function $C(e,t){t.unfinalizedDrafts_=t.drafts_.length;const n=t.drafts_[0];return e!==void 0&&e!==n?(n[wr].modified_&&(t1(t),ho(4)),$a(e)&&(e=Ah(t,e),t.parent_||Oh(t,e)),t.patches_&&ka("Patches").generateReplacementPatches_(n[wr].base_,e,t.patches_,t.inversePatches_)):e=Ah(t,n,[]),t1(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==wT?e:void 0}function Ah(e,t,n){if(Im(t))return t;const r=t[wr];if(!r)return Qu(t,(o,i)=>kC(e,r,t,o,i,n)),t;if(r.scope_!==e)return t;if(!r.modified_)return Oh(e,r.base_,!0),r.base_;if(!r.finalized_){r.finalized_=!0,r.scope_.unfinalizedDrafts_--;const o=r.copy_;let i=o,s=!1;r.type_===3&&(i=new Set(o),o.clear(),s=!0),Qu(i,(l,u)=>kC(e,r,o,l,u,n,s)),Oh(e,o,!1),n&&e.patches_&&ka("Patches").generatePatches_(r,n,e.patches_,e.inversePatches_)}return r.copy_}function kC(e,t,n,r,o,i,s){if(tc(o)){const l=i&&t&&t.type_!==3&&!Jy(t.assigned_,r)?i.concat(r):void 0,u=Ah(e,o,l);if(bT(n,r,u),tc(u))e.canAutoFreeze_=!1;else return}else s&&n.add(o);if($a(o)&&!Im(o)){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1)return;Ah(e,o),(!t||!t.scope_.parent_)&&Oh(e,o)}}function Oh(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&ax(t,n)}function Pz(e,t){const n=Array.isArray(e),r={type_:n?1:0,scope_:t?t.scope_:_T(),modified_:!1,finalized_:!1,assigned_:{},parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1};let o=r,i=lx;n&&(o=[r],i=ed);const{revoke:s,proxy:l}=Proxy.revocable(o,i);return r.draft_=l,r.revoke_=s,l}var lx={get(e,t){if(t===wr)return e;const n=Js(e);if(!Jy(n,t))return Az(e,n,t);const r=n[t];return e.finalized_||!$a(r)?r:r===h0(e.base_,t)?(m0(e),e.copy_[t]=o1(r,e)):r},has(e,t){return t in Js(e)},ownKeys(e){return Reflect.ownKeys(Js(e))},set(e,t,n){const r=ST(Js(e),t);if(r!=null&&r.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){const o=h0(Js(e),t),i=o==null?void 0:o[wr];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_[t]=!1,!0;if(Cz(n,o)&&(n!==void 0||Jy(e.base_,t)))return!0;m0(e),r1(e)}return e.copy_[t]===n&&(n!==void 0||t in e.copy_)||Number.isNaN(n)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=n,e.assigned_[t]=!0),!0},deleteProperty(e,t){return h0(e.base_,t)!==void 0||t in e.base_?(e.assigned_[t]=!1,m0(e),r1(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const n=Js(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{writable:!0,configurable:e.type_!==1||t!=="length",enumerable:r.enumerable,value:n[t]}},defineProperty(){ho(11)},getPrototypeOf(e){return ec(e.base_)},setPrototypeOf(){ho(12)}},ed={};Qu(lx,(e,t)=>{ed[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}});ed.deleteProperty=function(e,t){return ed.set.call(this,e,t,void 0)};ed.set=function(e,t,n){return lx.set.call(this,e[0],t,n,e[0])};function h0(e,t){const n=e[wr];return(n?Js(n):e)[t]}function Az(e,t,n){var o;const r=ST(t,n);return r?"value"in r?r.value:(o=r.get)==null?void 0:o.call(e.draft_):void 0}function ST(e,t){if(!(t in e))return;let n=ec(e);for(;n;){const r=Object.getOwnPropertyDescriptor(n,t);if(r)return r;n=ec(n)}}function r1(e){e.modified_||(e.modified_=!0,e.parent_&&r1(e.parent_))}function m0(e){e.copy_||(e.copy_=e1(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Oz=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(t,n,r)=>{if(typeof t=="function"&&typeof n!="function"){const i=n;n=t;const s=this;return function(u=i,...d){return s.produce(u,h=>n.call(this,h,...d))}}typeof n!="function"&&ho(6),r!==void 0&&typeof r!="function"&&ho(7);let o;if($a(t)){const i=CC(this),s=o1(t,void 0);let l=!0;try{o=n(s),l=!1}finally{l?t1(i):n1(i)}return EC(i,r),$C(o,i)}else if(!t||typeof t!="object"){if(o=n(t),o===void 0&&(o=t),o===wT&&(o=void 0),this.autoFreeze_&&ax(o,!0),r){const i=[],s=[];ka("Patches").generateReplacementPatches_(t,o,i,s),r(i,s)}return o}else ho(1,t)},this.produceWithPatches=(t,n)=>{if(typeof t=="function")return(s,...l)=>this.produceWithPatches(s,u=>t(u,...l));let r,o;return[this.produce(t,n,(s,l)=>{r=s,o=l}),r,o]},typeof(e==null?void 0:e.autoFreeze)=="boolean"&&this.setAutoFreeze(e.autoFreeze),typeof(e==null?void 0:e.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(e.useStrictShallowCopy)}createDraft(e){$a(e)||ho(8),tc(e)&&(e=Mz(e));const t=CC(this),n=o1(e,void 0);return n[wr].isManual_=!0,n1(t),n}finishDraft(e,t){const n=e&&e[wr];(!n||!n.isManual_)&&ho(9);const{scope_:r}=n;return EC(r,t),$C(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){const o=t[n];if(o.path.length===0&&o.op==="replace"){e=o.value;break}}n>-1&&(t=t.slice(n+1));const r=ka("Patches").applyPatches_;return tc(e)?r(e,t):this.produce(e,o=>r(o,t))}};function o1(e,t){const n=Nm(e)?ka("MapSet").proxyMap_(e,t):Dm(e)?ka("MapSet").proxySet_(e,t):Pz(e,t);return(t?t.scope_:_T()).drafts_.push(n),n}function Mz(e){return tc(e)||ho(10,e),ET(e)}function ET(e){if(!$a(e)||Im(e))return e;const t=e[wr];let n;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=e1(e,t.scope_.immer_.useStrictShallowCopy_)}else n=e1(e,!0);return Qu(n,(r,o)=>{bT(n,r,ET(o))}),t&&(t.finalized_=!1),n}var xr=new Oz,Nz=xr.produce;xr.produceWithPatches.bind(xr);xr.setAutoFreeze.bind(xr);xr.setUseStrictShallowCopy.bind(xr);xr.applyPatches.bind(xr);xr.createDraft.bind(xr);xr.finishDraft.bind(xr);const Dz=e=>(t,n,r)=>(r.setState=(o,i,...s)=>{const l=typeof o=="function"?Nz(o):o;return t(l,i,...s)},e(r.setState,n,r)),Iz=Dz;var CT={exports:{}},$T={},kT={exports:{}},RT={};/** + * @license React + * use-sync-external-store-shim.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. + */var nc=f;function Lz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Fz=typeof Object.is=="function"?Object.is:Lz,jz=nc.useState,zz=nc.useEffect,Bz=nc.useLayoutEffect,Uz=nc.useDebugValue;function Vz(e,t){var n=t(),r=jz({inst:{value:n,getSnapshot:t}}),o=r[0].inst,i=r[1];return Bz(function(){o.value=n,o.getSnapshot=t,g0(o)&&i({inst:o})},[e,n,t]),zz(function(){return g0(o)&&i({inst:o}),e(function(){g0(o)&&i({inst:o})})},[e]),Uz(n),n}function g0(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Fz(e,n)}catch{return!0}}function Wz(e,t){return t()}var Hz=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?Wz:Vz;RT.useSyncExternalStore=nc.useSyncExternalStore!==void 0?nc.useSyncExternalStore:Hz;kT.exports=RT;var Kz=kT.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.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. + */var Lm=f,Yz=Kz;function Gz(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var Xz=typeof Object.is=="function"?Object.is:Gz,Zz=Yz.useSyncExternalStore,qz=Lm.useRef,Qz=Lm.useEffect,Jz=Lm.useMemo,eB=Lm.useDebugValue;$T.useSyncExternalStoreWithSelector=function(e,t,n,r,o){var i=qz(null);if(i.current===null){var s={hasValue:!1,value:null};i.current=s}else s=i.current;i=Jz(function(){function u(y){if(!d){if(d=!0,h=y,y=r(y),o!==void 0&&s.hasValue){var x=s.value;if(o(x,y))return m=x}return m=y}if(x=m,Xz(h,y))return x;var _=r(y);return o!==void 0&&o(x,_)?x:(h=y,m=_)}var d=!1,h,m,g=n===void 0?null:n;return[function(){return u(t())},g===null?void 0:function(){return u(g())}]},[t,n,r,o]);var l=Zz(e,i[0],i[1]);return Qz(function(){s.hasValue=!0,s.value=l},[l]),eB(l),l};CT.exports=$T;var tB=CT.exports;const nB=lm(tB);var rB={VITE_BACKEND:"http://127.0.0.1:8080",BASE_URL:"/",MODE:"production",DEV:!1,PROD:!0,SSR:!1};const RC=e=>{let t;const n=new Set,r=(u,d)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const m=t;t=d??typeof h!="object"?h:Object.assign({},t,h),n.forEach(g=>g(t,m))}},o=()=>t,l={setState:r,getState:o,subscribe:u=>(n.add(u),()=>n.delete(u)),destroy:()=>{(rB?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}};return t=e(r,o,l),l},oB=e=>e?RC(e):RC,{useDebugValue:iB}=Fe,{useSyncExternalStoreWithSelector:sB}=nB;function aB(e,t=e.getState,n){const r=sB(e.subscribe,e.getState,e.getServerState||e.getState,t,n);return iB(r),r}const TC=(e,t)=>{const n=oB(e),r=(o,i=t)=>aB(n,o,i);return Object.assign(r,n),r},lB=(e,t)=>e?TC(e,t):TC,cB=1,uB=1e6;let v0=0;function dB(){return v0=(v0+1)%Number.MAX_VALUE,v0.toString()}const y0=new Map,PC=e=>{if(y0.has(e))return;const t=setTimeout(()=>{y0.delete(e),Tu({type:"REMOVE_TOAST",toastId:e})},uB);y0.set(e,t)},fB=(e,t)=>{switch(t.type){case"ADD_TOAST":return{...e,toasts:[t.toast,...e.toasts].slice(0,cB)};case"UPDATE_TOAST":return{...e,toasts:e.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?PC(n):e.toasts.forEach(r=>{PC(r.id)}),{...e,toasts:e.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(n=>n.id!==t.toastId)}}},Bp=[];let Up={toasts:[]};function Tu(e){Up=fB(Up,e),Bp.forEach(t=>{t(Up)})}function rl({...e}){const t=dB(),n=o=>Tu({type:"UPDATE_TOAST",toast:{...o,id:t}}),r=()=>Tu({type:"DISMISS_TOAST",toastId:t});return Tu({type:"ADD_TOAST",toast:{...e,id:t,open:!0,onOpenChange:o=>{o||r()}}}),{id:t,dismiss:r,update:n}}function Td(){const[e,t]=f.useState(Up);return f.useEffect(()=>(Bp.push(t),()=>{const n=Bp.indexOf(t);n>-1&&Bp.splice(n,1)}),[e]),{...e,toast:rl,dismiss:n=>Tu({type:"DISMISS_TOAST",toastId:n})}}const Zs={file:null,paintByExampleFile:null,customMask:null,imageHeight:0,imageWidth:0,isInpainting:!1,isPluginRunning:!1,isAdjustingMask:!1,disableShortCuts:!1,windowSize:{height:600,width:800},editorState:{baseBrushSize:sF,brushSizeScale:1,renders:[],extraMasks:[],prevExtraMasks:[],temporaryMasks:[],lineGroups:[],lastLineGroup:[],curLineGroup:[],redoRenders:[],redoCurLines:[],redoLineGroups:[]},interactiveSegState:{isInteractiveSeg:!1,tmpInteractiveSegMask:null,clicks:[]},cropperState:{x:0,y:0,width:512,height:512},extenderState:{x:0,y:0,width:512,height:512},isCropperExtenderResizing:!1,fileManagerState:{sortBy:xs.CTIME,sortOrder:$u.DESCENDING,layout:"masonry",searchText:"",inputDirectory:"",outputDirectory:""},serverConfig:{plugins:[],enableFileManager:!1,enableAutoSaving:!1,enableControlnet:!1,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",disableModelSwitch:!1,isDesktop:!1,samplers:["DPM++ 2M"]},settings:{model:{name:"lama",path:"lama",model_type:"inpaint",support_controlnet:!1,support_strength:!1,support_outpainting:!1,controlnets:[],support_freeu:!1,support_lcm_lora:!1,is_single_file_diffusers:!1,need_prompt:!1},enableControlnet:!1,showCropper:!1,showExtender:!1,extenderDirection:In.xy,enableDownloadMask:!1,enableManualInpainting:!1,enableUploadMask:!1,enableAutoExtractPrompt:!0,ldmSteps:30,ldmSampler:Zw.ddim,zitsWireframe:!0,cv2Radius:5,cv2Flag:qw.INPAINT_NS,prompt:"",negativePrompt:uF,seed:42,seedFixed:!1,sdMaskBlur:35,sdStrength:1,sdSteps:50,sdGuidanceScale:7.5,sdSampler:"DPM++ 2M",sdMatchHistograms:!1,sdScale:1,p2pImageGuidanceScale:1.5,controlnetConditioningScale:.4,controlnetMethod:"lllyasviel/control_v11p_sd15_canny",enableLCMLora:!1,enableFreeu:!1,freeuConfig:{s1:.9,s2:.2,b1:1.2,b2:1.4},powerpaintTask:kl.text_guided,adjustMaskKernelSize:12}},bt=lB()(_z(Iz((e,t)=>({...Zs,showPrevMask:async()=>{if(t().settings.showExtender)return;const{lastLineGroup:n,curLineGroup:r,prevExtraMasks:o,extraMasks:i}=t().editorState;if(r.length!==0||i.length!==0)return;const{imageWidth:s,imageHeight:l}=t(),u=Lp(s,l,[n],o,Ky);try{const d=await aC(u);e(h=>{h.editorState.temporaryMasks.push(d)})}catch(d){console.error(d);return}},hidePrevMask:()=>{e(n=>{n.editorState.temporaryMasks=[]})},getCurrentTargetFile:async()=>{const n=t().file,r=t().editorState.renders;let o=n;if(r.length>0){const i=r[r.length-1];o=await ku(i.currentSrc,n.name,n.type)}return o},runInpainting:async()=>{const{isInpainting:n,file:r,paintByExampleFile:o,imageWidth:i,imageHeight:s,settings:l,cropperState:u,extenderState:d}=t();if(n||r===null||t().settings.model.support_outpainting&&l.showExtender&&d.height===s&&d.width===i)return;const{lastLineGroup:h,curLineGroup:m,lineGroups:g,renders:y,prevExtraMasks:x,extraMasks:_}=t().editorState,C=m.length===0&&_.length===0&&!l.showExtender;let S=[],b=[];if(C===!0?(b=h,S=x):(b=m,S=_),b.length===0&&S===null&&!l.showExtender){rl({variant:"destructive",description:"Please draw mask on picture"});return}const E=[...g,b];e(M=>{M.isInpainting=!0});let k=r;if(C===!0){if(y.length>1){const M=y[y.length-2];k=await ku(M.currentSrc,r.name,r.type)}}else if(y.length>0){const M=y[y.length-1];k=await ku(M.currentSrc,r.name,r.type)}const P=Lp(i,s,[b],S);if(C){const M=await aC(P);e(A=>{A.editorState.temporaryMasks=[M]})}try{const M=await Lj(k,l,u,d,sC(P.toDataURL()),o),{blob:A,seed:O}=M;O&&t().setSeed(parseInt(O,10));const F=new Image;await Ip(F,A);const V=[...y,F];t().setImageSize(F.width,F.height),t().updateEditorState({renders:V,lineGroups:E,lastLineGroup:b,curLineGroup:[],extraMasks:[],prevExtraMasks:S})}catch(M){rl({variant:"destructive",description:M.message?M.message:M.toString()})}t().resetRedoState(),e(M=>{M.isInpainting=!1,M.editorState.temporaryMasks=[]})},runRenderablePlugin:async(n,r,o={upscale:1})=>{const{renders:i,lineGroups:s}=t().editorState;e(l=>{l.isPluginRunning=!0});try{const l=new Date,u=await t().getCurrentTargetFile(),d=await gT(n,r,u,o.upscale),{blob:h}=d;if(n){const y=new Image;await Ip(y,h),e(x=>{x.editorState.extraMasks.push(y)})}else{const y=new Image;await Ip(y,h),t().setImageSize(y.width,y.height);const x=[...i,y],_=[...s,[]];t().updateEditorState({renders:x,lineGroups:_})}const g=new Date().getTime()-l.getTime();rl({description:`Run ${r} successfully in ${g/1e3}s`})}catch(l){rl({variant:"destructive",description:l.message?l.message:l.toString()})}e(l=>{l.isPluginRunning=!1})},updateEditorState:n=>{e(r=>{r.editorState={...r.editorState,...n}})},cleanCurLineGroup:()=>{t().updateEditorState({curLineGroup:[]})},handleCanvasMouseDown:n=>{let r=[];const o=t();o.runMannually()&&(r=[...o.editorState.curLineGroup]),r.push({size:o.getBrushSize(),pts:[n]}),e(i=>{i.editorState.curLineGroup=r})},handleCanvasMouseMove:n=>{e(r=>{const o=r.editorState.curLineGroup;o.length&&o[o.length-1].pts.push(n)})},runMannually:()=>{const n=t();return n.settings.enableManualInpainting||n.settings.model.model_type!==is},getIsProcessing:()=>t().isInpainting||t().isPluginRunning||t().isAdjustingMask,isSD:()=>t().settings.model.model_type!==is,undoDisabled:()=>{const n=t().editorState;if(n.renders.length>0)return!1;if(t().runMannually()){if(n.curLineGroup.length===0)return!0}else if(n.renders.length===0)return!0;return!1},undo:()=>{t().runMannually()&&t().editorState.curLineGroup.length!==0?e(n=>{const r=n.editorState;if(r.curLineGroup.length===0)return;r.lastLineGroup=[];const o=r.curLineGroup.pop();r.redoCurLines.push(o)}):e(n=>{const r=n.editorState;if(r.renders.length===0||r.lineGroups.length===0)return;const o=r.lineGroups.pop();r.redoLineGroups.push(o),r.redoCurLines=[],r.curLineGroup=[];const i=r.renders.pop();r.redoRenders.push(i)})},redoDisabled:()=>{const n=t().editorState;if(n.redoRenders.length>0)return!1;if(t().runMannually()){if(n.redoCurLines.length===0)return!0}else if(n.redoRenders.length===0)return!0;return!1},redo:()=>{t().runMannually()&&t().editorState.redoCurLines.length!==0?e(n=>{const r=n.editorState;if(r.redoCurLines.length===0)return;const o=r.redoCurLines.pop();r.curLineGroup.push(o)}):e(n=>{const r=n.editorState;if(r.redoRenders.length===0||r.redoLineGroups.length===0)return;const o=r.redoLineGroups.pop();r.lineGroups.push(o),r.curLineGroup=[];const i=r.redoRenders.pop();r.renders.push(i)})},resetRedoState:()=>{e(n=>{n.editorState.redoCurLines=[],n.editorState.redoLineGroups=[],n.editorState.redoRenders=[]})},updateAppState:n=>{e(()=>n)},getBrushSize:()=>t().editorState.baseBrushSize*t().editorState.brushSizeScale,showPromptInput:()=>{const n=t().settings.model;return n.model_type!==is&&n.name!==YR},setServerConfig:n=>{e(r=>{r.serverConfig=n,r.settings.enableControlnet=n.enableControlnet,r.settings.controlnetMethod=n.controlnetMethod})},updateSettings:n=>{e(r=>{r.settings={...r.settings,...n}})},setModel:n=>{e(r=>{r.settings.model=n,n.support_controlnet&&!n.controlnets.includes(r.settings.controlnetMethod)&&(r.settings.controlnetMethod=n.controlnets[0])})},updateFileManagerState:n=>{e(r=>{r.fileManagerState={...r.fileManagerState,...n}})},updateInteractiveSegState:n=>{e(r=>({...r,interactiveSegState:{...r.interactiveSegState,...n}}))},resetInteractiveSegState:()=>{t().updateInteractiveSegState(Zs.interactiveSegState)},handleInteractiveSegAccept:()=>{e(n=>{n.interactiveSegState.tmpInteractiveSegMask&&n.editorState.extraMasks.push(n.interactiveSegState.tmpInteractiveSegMask),n.interactiveSegState={...Zs.interactiveSegState}})},setIsInpainting:n=>e(r=>{r.isInpainting=n}),setFile:async n=>{if(t().settings.enableAutoExtractPrompt)try{const r=await Hj(n);r.prompt&&e(o=>{o.settings.prompt=r.prompt}),r.negative_prompt&&e(o=>{o.settings.negativePrompt=r.negative_prompt})}catch(r){rl({variant:"destructive",description:r.message?r.message:r.toString()})}e(r=>{r.file=n,r.interactiveSegState=Zs.interactiveSegState,r.editorState=Zs.editorState,r.cropperState=Zs.cropperState})},setCustomFile:n=>e(r=>{r.customMask=n}),setBaseBrushSize:n=>e(r=>{r.editorState.baseBrushSize=n}),setImageSize:(n,r)=>{e(o=>{o.imageWidth=n,o.imageHeight=r,o.editorState.brushSizeScale=Math.max(Math.min(n,r),512)/512}),t().resetExtender(n,r)},setCropperX:n=>e(r=>{r.cropperState.x=n}),setCropperY:n=>e(r=>{r.cropperState.y=n}),setCropperWidth:n=>e(r=>{r.cropperState.width=n}),setCropperHeight:n=>e(r=>{r.cropperState.height=n}),setExtenderX:n=>e(r=>{r.extenderState.x=n}),setExtenderY:n=>e(r=>{r.extenderState.y=n}),setExtenderWidth:n=>e(r=>{r.extenderState.width=n}),setExtenderHeight:n=>e(r=>{r.extenderState.height=n}),setIsCropperExtenderResizing:n=>e(r=>{r.isCropperExtenderResizing=n}),updateExtenderDirection:n=>{console.log(`updateExtenderDirection: ${JSON.stringify(t().extenderState)}`),e(r=>{r.settings.extenderDirection=n,r.extenderState.x=0,r.extenderState.y=0,r.extenderState.width=r.imageWidth,r.extenderState.height=r.imageHeight}),t().updateExtenderByBuiltIn(n,1.5)},updateExtenderByBuiltIn:(n,r)=>{const o={...Zs.extenderState};let{x:i,y:s,width:l,height:u}=o;const{imageWidth:d,imageHeight:h}=t();switch(l=d,u=h,n){case In.x:i=-Math.ceil(d*(r-1)/2),l=Math.ceil(d*r);break;case In.y:s=-Math.ceil(h*(r-1)/2),u=Math.ceil(h*r);break;case In.xy:i=-Math.ceil(d*(r-1)/2),s=-Math.ceil(h*(r-1)/2),l=Math.ceil(d*r),u=Math.ceil(h*r);break}e(m=>{m.extenderState.x=i,m.extenderState.y=s,m.extenderState.width=l,m.extenderState.height=u})},resetExtender:(n,r)=>{e(o=>{o.extenderState.x=0,o.extenderState.y=0,o.extenderState.width=n,o.extenderState.height=r})},setSeed:n=>e(r=>{r.settings.seed=n}),adjustMask:async n=>{const{imageWidth:r,imageHeight:o}=t(),{curLineGroup:i,extraMasks:s}=t().editorState,{adjustMaskKernelSize:l}=t().settings;if(i.length===0&&s.length===0)return;e(g=>{g.isAdjustingMask=!0});const u=Lp(r,o,[i],s,Ky),d=sC(u.toDataURL()),h=await Kj(d,n,l),m=await fF(h);e(g=>{g.editorState.extraMasks=[m],g.editorState.curLineGroup=[]}),e(g=>{g.isAdjustingMask=!1})},clearMask:()=>{e(n=>{n.editorState.extraMasks=[],n.editorState.curLineGroup=[]})}})),{name:"ZUSTAND_STATE",version:1,partialize:e=>Object.fromEntries(Object.entries(e).filter(([t])=>["fileManagerState","settings"].includes(t)))}),Sz),Pd=f.forwardRef(({className:e,type:t,...n},r)=>{const o=bt(l=>l.updateAppState),i=()=>{o({disableShortCuts:!0})},s=()=>{o({disableShortCuts:!1})};return v.jsx("input",{type:t,className:Ce("flex h-8 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e),ref:r,autoComplete:"off",tabIndex:-1,onFocus:i,onBlur:s,...n})});Pd.displayName="Input";const Gn=f.forwardRef(({numberValue:e,allowFloat:t,onNumberValueChange:n,...r},o)=>{const[i,s]=f.useState(e.toString());f.useEffect(()=>{i!==e.toString()+"."&&s(e.toString())},[e]);const l=u=>{let h=u.target.value;if(t){if(h=h.replace(/[^0-9.]/g,"").replace(/(\..*?)\..*/g,"$1"),h.length===0){n(0);return}n(parseFloat(h))}else{if(h=h.replace(/\D/g,""),h.length===0){n(0);return}n(parseInt(h,10))}s(h)};return v.jsx(Pd,{ref:o,value:i,onInput:l,...r})});function ue(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function pB(e,t){const n=f.createContext(t);function r(i){const{children:s,...l}=i,u=f.useMemo(()=>l,Object.values(l));return f.createElement(n.Provider,{value:u},s)}function o(i){const s=f.useContext(n);if(s)return s;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${e}\``)}return r.displayName=e+"Provider",[r,o]}function An(e,t=[]){let n=[];function r(i,s){const l=f.createContext(s),u=n.length;n=[...n,s];function d(m){const{scope:g,children:y,...x}=m,_=(g==null?void 0:g[e][u])||l,C=f.useMemo(()=>x,Object.values(x));return f.createElement(_.Provider,{value:C},y)}function h(m,g){const y=(g==null?void 0:g[e][u])||l,x=f.useContext(y);if(x)return x;if(s!==void 0)return s;throw new Error(`\`${m}\` must be used within \`${i}\``)}return d.displayName=i+"Provider",[d,h]}const o=()=>{const i=n.map(s=>f.createContext(s));return function(l){const u=(l==null?void 0:l[e])||i;return f.useMemo(()=>({[`__scope${e}`]:{...l,[e]:u}}),[l,u])}};return o.scopeName=e,[r,hB(o,...t)]}function hB(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(i){const s=r.reduce((l,{useScope:u,scopeName:d})=>{const m=u(i)[`__scope${d}`];return{...l,...m}},{});return f.useMemo(()=>({[`__scope${t.scopeName}`]:s}),[s])}};return n.scopeName=t.scopeName,n}const mB=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],Pe=mB.reduce((e,t)=>{const n=f.forwardRef((r,o)=>{const{asChild:i,...s}=r,l=i?Wo:t;return f.useEffect(()=>{window[Symbol.for("radix-ui")]=!0},[]),f.createElement(l,Y({},s,{ref:o}))});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function cx(e,t){e&&Os.flushSync(()=>e.dispatchEvent(t))}function Ft(e){const t=f.useRef(e);return f.useEffect(()=>{t.current=e}),f.useMemo(()=>(...n)=>{var r;return(r=t.current)===null||r===void 0?void 0:r.call(t,...n)},[])}function gB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e);f.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r),()=>t.removeEventListener("keydown",r)},[n,t])}const i1="dismissableLayer.update",vB="dismissableLayer.pointerDownOutside",yB="dismissableLayer.focusOutside";let AC;const TT=f.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),yc=f.forwardRef((e,t)=>{var n;const{disableOutsidePointerEvents:r=!1,onEscapeKeyDown:o,onPointerDownOutside:i,onFocusOutside:s,onInteractOutside:l,onDismiss:u,...d}=e,h=f.useContext(TT),[m,g]=f.useState(null),y=(n=m==null?void 0:m.ownerDocument)!==null&&n!==void 0?n:globalThis==null?void 0:globalThis.document,[,x]=f.useState({}),_=Be(t,O=>g(O)),C=Array.from(h.layers),[S]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),b=C.indexOf(S),E=m?C.indexOf(m):-1,k=h.layersWithOutsidePointerEventsDisabled.size>0,P=E>=b,M=xB(O=>{const F=O.target,V=[...h.branches].some(J=>J.contains(F));!P||V||(i==null||i(O),l==null||l(O),O.defaultPrevented||u==null||u())},y),A=bB(O=>{const F=O.target;[...h.branches].some(J=>J.contains(F))||(s==null||s(O),l==null||l(O),O.defaultPrevented||u==null||u())},y);return gB(O=>{E===h.layers.size-1&&(o==null||o(O),!O.defaultPrevented&&u&&(O.preventDefault(),u()))},y),f.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(AC=y.body.style.pointerEvents,y.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),OC(),()=>{r&&h.layersWithOutsidePointerEventsDisabled.size===1&&(y.body.style.pointerEvents=AC)}},[m,y,r,h]),f.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),OC())},[m,h]),f.useEffect(()=>{const O=()=>x({});return document.addEventListener(i1,O),()=>document.removeEventListener(i1,O)},[]),f.createElement(Pe.div,Y({},d,{ref:_,style:{pointerEvents:k?P?"auto":"none":void 0,...e.style},onFocusCapture:ue(e.onFocusCapture,A.onFocusCapture),onBlurCapture:ue(e.onBlurCapture,A.onBlurCapture),onPointerDownCapture:ue(e.onPointerDownCapture,M.onPointerDownCapture)}))}),wB=f.forwardRef((e,t)=>{const n=f.useContext(TT),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),f.createElement(Pe.div,Y({},e,{ref:o}))});function xB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1),o=f.useRef(()=>{});return f.useEffect(()=>{const i=l=>{if(l.target&&!r.current){let h=function(){PT(vB,n,d,{discrete:!0})};var u=h;const d={originalEvent:l};l.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=h,t.addEventListener("click",o.current,{once:!0})):h()}else t.removeEventListener("click",o.current);r.current=!1},s=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(s),t.removeEventListener("pointerdown",i),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function bB(e,t=globalThis==null?void 0:globalThis.document){const n=Ft(e),r=f.useRef(!1);return f.useEffect(()=>{const o=i=>{i.target&&!r.current&&PT(yB,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function OC(){const e=new CustomEvent(i1);document.dispatchEvent(e)}function PT(e,t,n,{discrete:r}){const o=n.originalEvent.target,i=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const _B=yc,SB=wB,Pn=globalThis!=null&&globalThis.document?f.useLayoutEffect:()=>{},EB=jD.useId||(()=>{});let CB=0;function nr(e){const[t,n]=f.useState(EB());return Pn(()=>{e||n(r=>r??String(CB++))},[e]),e||(t?`radix-${t}`:"")}const $B=["top","right","bottom","left"],Cs=Math.min,pr=Math.max,Mh=Math.round,ip=Math.floor,$s=e=>({x:e,y:e}),kB={left:"right",right:"left",bottom:"top",top:"bottom"},RB={start:"end",end:"start"};function s1(e,t,n){return pr(e,Cs(t,n))}function yi(e,t){return typeof e=="function"?e(t):e}function wi(e){return e.split("-")[0]}function wc(e){return e.split("-")[1]}function ux(e){return e==="x"?"y":"x"}function dx(e){return e==="y"?"height":"width"}function xc(e){return["top","bottom"].includes(wi(e))?"y":"x"}function fx(e){return ux(xc(e))}function TB(e,t,n){n===void 0&&(n=!1);const r=wc(e),o=fx(e),i=dx(o);let s=o==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(s=Nh(s)),[s,Nh(s)]}function PB(e){const t=Nh(e);return[a1(e),t,a1(t)]}function a1(e){return e.replace(/start|end/g,t=>RB[t])}function AB(e,t,n){const r=["left","right"],o=["right","left"],i=["top","bottom"],s=["bottom","top"];switch(e){case"top":case"bottom":return n?t?o:r:t?r:o;case"left":case"right":return t?i:s;default:return[]}}function OB(e,t,n,r){const o=wc(e);let i=AB(wi(e),n==="start",r);return o&&(i=i.map(s=>s+"-"+o),t&&(i=i.concat(i.map(a1)))),i}function Nh(e){return e.replace(/left|right|bottom|top/g,t=>kB[t])}function MB(e){return{top:0,right:0,bottom:0,left:0,...e}}function AT(e){return typeof e!="number"?MB(e):{top:e,right:e,bottom:e,left:e}}function Dh(e){return{...e,top:e.y,left:e.x,right:e.x+e.width,bottom:e.y+e.height}}function MC(e,t,n){let{reference:r,floating:o}=e;const i=xc(t),s=fx(t),l=dx(s),u=wi(t),d=i==="y",h=r.x+r.width/2-o.width/2,m=r.y+r.height/2-o.height/2,g=r[l]/2-o[l]/2;let y;switch(u){case"top":y={x:h,y:r.y-o.height};break;case"bottom":y={x:h,y:r.y+r.height};break;case"right":y={x:r.x+r.width,y:m};break;case"left":y={x:r.x-o.width,y:m};break;default:y={x:r.x,y:r.y}}switch(wc(t)){case"start":y[s]-=g*(n&&d?-1:1);break;case"end":y[s]+=g*(n&&d?-1:1);break}return y}const NB=async(e,t,n)=>{const{placement:r="bottom",strategy:o="absolute",middleware:i=[],platform:s}=n,l=i.filter(Boolean),u=await(s.isRTL==null?void 0:s.isRTL(t));let d=await s.getElementRects({reference:e,floating:t,strategy:o}),{x:h,y:m}=MC(d,r,u),g=r,y={},x=0;for(let _=0;_({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:o,rects:i,platform:s,elements:l,middlewareData:u}=t,{element:d,padding:h=0}=yi(e,t)||{};if(d==null)return{};const m=AT(h),g={x:n,y:r},y=fx(o),x=dx(y),_=await s.getDimensions(d),C=y==="y",S=C?"top":"left",b=C?"bottom":"right",E=C?"clientHeight":"clientWidth",k=i.reference[x]+i.reference[y]-g[y]-i.floating[x],P=g[y]-i.reference[y],M=await(s.getOffsetParent==null?void 0:s.getOffsetParent(d));let A=M?M[E]:0;(!A||!await(s.isElement==null?void 0:s.isElement(M)))&&(A=l.floating[E]||i.floating[x]);const O=k/2-P/2,F=A/2-_[x]/2-1,V=Cs(m[S],F),J=Cs(m[b],F),G=V,ae=A-_[x]-J,U=A/2-_[x]/2+O,te=s1(G,U,ae),L=!u.arrow&&wc(o)!=null&&U!=te&&i.reference[x]/2-(UG<=0)){var F,V;const G=(((F=i.flip)==null?void 0:F.index)||0)+1,ae=P[G];if(ae)return{data:{index:G,overflows:O},reset:{placement:ae}};let U=(V=O.filter(te=>te.overflows[0]<=0).sort((te,L)=>te.overflows[1]-L.overflows[1])[0])==null?void 0:V.placement;if(!U)switch(y){case"bestFit":{var J;const te=(J=O.map(L=>[L.placement,L.overflows.filter(ie=>ie>0).reduce((ie,K)=>ie+K,0)]).sort((L,ie)=>L[1]-ie[1])[0])==null?void 0:J[0];te&&(U=te);break}case"initialPlacement":U=l;break}if(o!==U)return{reset:{placement:U}}}return{}}}};function DC(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function IC(e){return $B.some(t=>e[t]>=0)}const IB=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...o}=yi(e,t);switch(r){case"referenceHidden":{const i=await td(t,{...o,elementContext:"reference"}),s=DC(i,n.reference);return{data:{referenceHiddenOffsets:s,referenceHidden:IC(s)}}}case"escaped":{const i=await td(t,{...o,altBoundary:!0}),s=DC(i,n.floating);return{data:{escapedOffsets:s,escaped:IC(s)}}}default:return{}}}}};async function LB(e,t){const{placement:n,platform:r,elements:o}=e,i=await(r.isRTL==null?void 0:r.isRTL(o.floating)),s=wi(n),l=wc(n),u=xc(n)==="y",d=["left","top"].includes(s)?-1:1,h=i&&u?-1:1,m=yi(t,e);let{mainAxis:g,crossAxis:y,alignmentAxis:x}=typeof m=="number"?{mainAxis:m,crossAxis:0,alignmentAxis:null}:{mainAxis:0,crossAxis:0,alignmentAxis:null,...m};return l&&typeof x=="number"&&(y=l==="end"?x*-1:x),u?{x:y*h,y:g*d}:{x:g*d,y:y*h}}const FB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){const{x:n,y:r}=t,o=await LB(t,e);return{x:n+o.x,y:r+o.y,data:o}}}},jB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:o}=t,{mainAxis:i=!0,crossAxis:s=!1,limiter:l={fn:C=>{let{x:S,y:b}=C;return{x:S,y:b}}},...u}=yi(e,t),d={x:n,y:r},h=await td(t,u),m=xc(wi(o)),g=ux(m);let y=d[g],x=d[m];if(i){const C=g==="y"?"top":"left",S=g==="y"?"bottom":"right",b=y+h[C],E=y-h[S];y=s1(b,y,E)}if(s){const C=m==="y"?"top":"left",S=m==="y"?"bottom":"right",b=x+h[C],E=x-h[S];x=s1(b,x,E)}const _=l.fn({...t,[g]:y,[m]:x});return{..._,data:{x:_.x-n,y:_.y-r}}}}},zB=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:o,rects:i,middlewareData:s}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=yi(e,t),h={x:n,y:r},m=xc(o),g=ux(m);let y=h[g],x=h[m];const _=yi(l,t),C=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(u){const E=g==="y"?"height":"width",k=i.reference[g]-i.floating[E]+C.mainAxis,P=i.reference[g]+i.reference[E]-C.mainAxis;yP&&(y=P)}if(d){var S,b;const E=g==="y"?"width":"height",k=["top","left"].includes(wi(o)),P=i.reference[m]-i.floating[E]+(k&&((S=s.offset)==null?void 0:S[m])||0)+(k?0:C.crossAxis),M=i.reference[m]+i.reference[E]+(k?0:((b=s.offset)==null?void 0:b[m])||0)-(k?C.crossAxis:0);xM&&(x=M)}return{[g]:y,[m]:x}}}},BB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:n,rects:r,platform:o,elements:i}=t,{apply:s=()=>{},...l}=yi(e,t),u=await td(t,l),d=wi(n),h=wc(n),m=xc(n)==="y",{width:g,height:y}=r.floating;let x,_;d==="top"||d==="bottom"?(x=d,_=h===(await(o.isRTL==null?void 0:o.isRTL(i.floating))?"start":"end")?"left":"right"):(_=d,x=h==="end"?"top":"bottom");const C=y-u[x],S=g-u[_],b=!t.middlewareData.shift;let E=C,k=S;if(m){const M=g-u.left-u.right;k=h||b?Cs(S,M):M}else{const M=y-u.top-u.bottom;E=h||b?Cs(C,M):M}if(b&&!h){const M=pr(u.left,0),A=pr(u.right,0),O=pr(u.top,0),F=pr(u.bottom,0);m?k=g-2*(M!==0||A!==0?M+A:pr(u.left,u.right)):E=y-2*(O!==0||F!==0?O+F:pr(u.top,u.bottom))}await s({...t,availableWidth:k,availableHeight:E});const P=await o.getDimensions(i.floating);return g!==P.width||y!==P.height?{reset:{rects:!0}}:{}}}};function ks(e){return OT(e)?(e.nodeName||"").toLowerCase():"#document"}function vr(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Ci(e){var t;return(t=(OT(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function OT(e){return e instanceof Node||e instanceof vr(e).Node}function xi(e){return e instanceof Element||e instanceof vr(e).Element}function Ho(e){return e instanceof HTMLElement||e instanceof vr(e).HTMLElement}function LC(e){return typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof vr(e).ShadowRoot}function Ad(e){const{overflow:t,overflowX:n,overflowY:r,display:o}=Xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(o)}function UB(e){return["table","td","th"].includes(ks(e))}function px(e){const t=hx(),n=Xr(e);return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function VB(e){let t=rc(e);for(;Ho(t)&&!Fm(t);){if(px(t))return t;t=rc(t)}return null}function hx(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function Fm(e){return["html","body","#document"].includes(ks(e))}function Xr(e){return vr(e).getComputedStyle(e)}function jm(e){return xi(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.pageXOffset,scrollTop:e.pageYOffset}}function rc(e){if(ks(e)==="html")return e;const t=e.assignedSlot||e.parentNode||LC(e)&&e.host||Ci(e);return LC(t)?t.host:t}function MT(e){const t=rc(e);return Fm(t)?e.ownerDocument?e.ownerDocument.body:e.body:Ho(t)&&Ad(t)?t:MT(t)}function nd(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const o=MT(e),i=o===((r=e.ownerDocument)==null?void 0:r.body),s=vr(o);return i?t.concat(s,s.visualViewport||[],Ad(o)?o:[],s.frameElement&&n?nd(s.frameElement):[]):t.concat(o,nd(o,[],n))}function NT(e){const t=Xr(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const o=Ho(e),i=o?e.offsetWidth:n,s=o?e.offsetHeight:r,l=Mh(n)!==i||Mh(r)!==s;return l&&(n=i,r=s),{width:n,height:r,$:l}}function mx(e){return xi(e)?e:e.contextElement}function Rl(e){const t=mx(e);if(!Ho(t))return $s(1);const n=t.getBoundingClientRect(),{width:r,height:o,$:i}=NT(t);let s=(i?Mh(n.width):n.width)/r,l=(i?Mh(n.height):n.height)/o;return(!s||!Number.isFinite(s))&&(s=1),(!l||!Number.isFinite(l))&&(l=1),{x:s,y:l}}const WB=$s(0);function DT(e){const t=vr(e);return!hx()||!t.visualViewport?WB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function HB(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==vr(e)?!1:t}function Ra(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const o=e.getBoundingClientRect(),i=mx(e);let s=$s(1);t&&(r?xi(r)&&(s=Rl(r)):s=Rl(e));const l=HB(i,n,r)?DT(i):$s(0);let u=(o.left+l.x)/s.x,d=(o.top+l.y)/s.y,h=o.width/s.x,m=o.height/s.y;if(i){const g=vr(i),y=r&&xi(r)?vr(r):r;let x=g.frameElement;for(;x&&r&&y!==g;){const _=Rl(x),C=x.getBoundingClientRect(),S=Xr(x),b=C.left+(x.clientLeft+parseFloat(S.paddingLeft))*_.x,E=C.top+(x.clientTop+parseFloat(S.paddingTop))*_.y;u*=_.x,d*=_.y,h*=_.x,m*=_.y,u+=b,d+=E,x=vr(x).frameElement}}return Dh({width:h,height:m,x:u,y:d})}function KB(e){let{rect:t,offsetParent:n,strategy:r}=e;const o=Ho(n),i=Ci(n);if(n===i)return t;let s={scrollLeft:0,scrollTop:0},l=$s(1);const u=$s(0);if((o||!o&&r!=="fixed")&&((ks(n)!=="body"||Ad(i))&&(s=jm(n)),Ho(n))){const d=Ra(n);l=Rl(n),u.x=d.x+n.clientLeft,u.y=d.y+n.clientTop}return{width:t.width*l.x,height:t.height*l.y,x:t.x*l.x-s.scrollLeft*l.x+u.x,y:t.y*l.y-s.scrollTop*l.y+u.y}}function YB(e){return Array.from(e.getClientRects())}function IT(e){return Ra(Ci(e)).left+jm(e).scrollLeft}function GB(e){const t=Ci(e),n=jm(e),r=e.ownerDocument.body,o=pr(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=pr(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let s=-n.scrollLeft+IT(e);const l=-n.scrollTop;return Xr(r).direction==="rtl"&&(s+=pr(t.clientWidth,r.clientWidth)-o),{width:o,height:i,x:s,y:l}}function XB(e,t){const n=vr(e),r=Ci(e),o=n.visualViewport;let i=r.clientWidth,s=r.clientHeight,l=0,u=0;if(o){i=o.width,s=o.height;const d=hx();(!d||d&&t==="fixed")&&(l=o.offsetLeft,u=o.offsetTop)}return{width:i,height:s,x:l,y:u}}function ZB(e,t){const n=Ra(e,!0,t==="fixed"),r=n.top+e.clientTop,o=n.left+e.clientLeft,i=Ho(e)?Rl(e):$s(1),s=e.clientWidth*i.x,l=e.clientHeight*i.y,u=o*i.x,d=r*i.y;return{width:s,height:l,x:u,y:d}}function FC(e,t,n){let r;if(t==="viewport")r=XB(e,n);else if(t==="document")r=GB(Ci(e));else if(xi(t))r=ZB(t,n);else{const o=DT(e);r={...t,x:t.x-o.x,y:t.y-o.y}}return Dh(r)}function LT(e,t){const n=rc(e);return n===t||!xi(n)||Fm(n)?!1:Xr(n).position==="fixed"||LT(n,t)}function qB(e,t){const n=t.get(e);if(n)return n;let r=nd(e,[],!1).filter(l=>xi(l)&&ks(l)!=="body"),o=null;const i=Xr(e).position==="fixed";let s=i?rc(e):e;for(;xi(s)&&!Fm(s);){const l=Xr(s),u=px(s);!u&&l.position==="fixed"&&(o=null),(i?!u&&!o:!u&&l.position==="static"&&!!o&&["absolute","fixed"].includes(o.position)||Ad(s)&&!u&<(e,s))?r=r.filter(h=>h!==s):o=l,s=rc(s)}return t.set(e,r),r}function QB(e){let{element:t,boundary:n,rootBoundary:r,strategy:o}=e;const s=[...n==="clippingAncestors"?qB(t,this._c):[].concat(n),r],l=s[0],u=s.reduce((d,h)=>{const m=FC(t,h,o);return d.top=pr(m.top,d.top),d.right=Cs(m.right,d.right),d.bottom=Cs(m.bottom,d.bottom),d.left=pr(m.left,d.left),d},FC(t,l,o));return{width:u.right-u.left,height:u.bottom-u.top,x:u.left,y:u.top}}function JB(e){return NT(e)}function eU(e,t,n){const r=Ho(t),o=Ci(t),i=n==="fixed",s=Ra(e,!0,i,t);let l={scrollLeft:0,scrollTop:0};const u=$s(0);if(r||!r&&!i)if((ks(t)!=="body"||Ad(o))&&(l=jm(t)),r){const d=Ra(t,!0,i,t);u.x=d.x+t.clientLeft,u.y=d.y+t.clientTop}else o&&(u.x=IT(o));return{x:s.left+l.scrollLeft-u.x,y:s.top+l.scrollTop-u.y,width:s.width,height:s.height}}function jC(e,t){return!Ho(e)||Xr(e).position==="fixed"?null:t?t(e):e.offsetParent}function FT(e,t){const n=vr(e);if(!Ho(e))return n;let r=jC(e,t);for(;r&&UB(r)&&Xr(r).position==="static";)r=jC(r,t);return r&&(ks(r)==="html"||ks(r)==="body"&&Xr(r).position==="static"&&!px(r))?n:r||VB(e)||n}const tU=async function(e){let{reference:t,floating:n,strategy:r}=e;const o=this.getOffsetParent||FT,i=this.getDimensions;return{reference:eU(t,await o(n),r),floating:{x:0,y:0,...await i(n)}}};function nU(e){return Xr(e).direction==="rtl"}const rU={convertOffsetParentRelativeRectToViewportRelativeRect:KB,getDocumentElement:Ci,getClippingRect:QB,getOffsetParent:FT,getElementRects:tU,getClientRects:YB,getDimensions:JB,getScale:Rl,isElement:xi,isRTL:nU};function oU(e,t){let n=null,r;const o=Ci(e);function i(){clearTimeout(r),n&&n.disconnect(),n=null}function s(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),i();const{left:d,top:h,width:m,height:g}=e.getBoundingClientRect();if(l||t(),!m||!g)return;const y=ip(h),x=ip(o.clientWidth-(d+m)),_=ip(o.clientHeight-(h+g)),C=ip(d),b={rootMargin:-y+"px "+-x+"px "+-_+"px "+-C+"px",threshold:pr(0,Cs(1,u))||1};let E=!0;function k(P){const M=P[0].intersectionRatio;if(M!==u){if(!E)return s();M?s(!1,M):r=setTimeout(()=>{s(!1,1e-7)},100)}E=!1}try{n=new IntersectionObserver(k,{...b,root:o.ownerDocument})}catch{n=new IntersectionObserver(k,b)}n.observe(e)}return s(!0),i}function iU(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:o=!0,ancestorResize:i=!0,elementResize:s=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=mx(e),h=o||i?[...d?nd(d):[],...nd(t)]:[];h.forEach(S=>{o&&S.addEventListener("scroll",n,{passive:!0}),i&&S.addEventListener("resize",n)});const m=d&&l?oU(d,n):null;let g=-1,y=null;s&&(y=new ResizeObserver(S=>{let[b]=S;b&&b.target===d&&y&&(y.unobserve(t),cancelAnimationFrame(g),g=requestAnimationFrame(()=>{y&&y.observe(t)})),n()}),d&&!u&&y.observe(d),y.observe(t));let x,_=u?Ra(e):null;u&&C();function C(){const S=Ra(e);_&&(S.x!==_.x||S.y!==_.y||S.width!==_.width||S.height!==_.height)&&n(),_=S,x=requestAnimationFrame(C)}return n(),()=>{h.forEach(S=>{o&&S.removeEventListener("scroll",n),i&&S.removeEventListener("resize",n)}),m&&m(),y&&y.disconnect(),y=null,u&&cancelAnimationFrame(x)}}const sU=(e,t,n)=>{const r=new Map,o={platform:rU,...n},i={...o.platform,_c:r};return NB(e,t,{...o,platform:i})},aU=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:o}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?NC({element:r.current,padding:o}).fn(n):{}:r?NC({element:r,padding:o}).fn(n):{}}}};var Vp=typeof document<"u"?f.useLayoutEffect:f.useEffect;function Ih(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,o;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!Ih(e[r],t[r]))return!1;return!0}if(o=Object.keys(e),n=o.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,o[r]))return!1;for(r=n;r--!==0;){const i=o[r];if(!(i==="_owner"&&e.$$typeof)&&!Ih(e[i],t[i]))return!1}return!0}return e!==e&&t!==t}function jT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function zC(e,t){const n=jT(e);return Math.round(t*n)/n}function BC(e){const t=f.useRef(e);return Vp(()=>{t.current=e}),t}function lU(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:o,elements:{reference:i,floating:s}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[h,m]=f.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[g,y]=f.useState(r);Ih(g,r)||y(r);const[x,_]=f.useState(null),[C,S]=f.useState(null),b=f.useCallback(L=>{L!=M.current&&(M.current=L,_(L))},[_]),E=f.useCallback(L=>{L!==A.current&&(A.current=L,S(L))},[S]),k=i||x,P=s||C,M=f.useRef(null),A=f.useRef(null),O=f.useRef(h),F=BC(u),V=BC(o),J=f.useCallback(()=>{if(!M.current||!A.current)return;const L={placement:t,strategy:n,middleware:g};V.current&&(L.platform=V.current),sU(M.current,A.current,L).then(ie=>{const K={...ie,isPositioned:!0};G.current&&!Ih(O.current,K)&&(O.current=K,Os.flushSync(()=>{m(K)}))})},[g,t,n,V]);Vp(()=>{d===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,m(L=>({...L,isPositioned:!1})))},[d]);const G=f.useRef(!1);Vp(()=>(G.current=!0,()=>{G.current=!1}),[]),Vp(()=>{if(k&&(M.current=k),P&&(A.current=P),k&&P){if(F.current)return F.current(k,P,J);J()}},[k,P,J,F]);const ae=f.useMemo(()=>({reference:M,floating:A,setReference:b,setFloating:E}),[b,E]),U=f.useMemo(()=>({reference:k,floating:P}),[k,P]),te=f.useMemo(()=>{const L={position:n,left:0,top:0};if(!U.floating)return L;const ie=zC(U.floating,h.x),K=zC(U.floating,h.y);return l?{...L,transform:"translate("+ie+"px, "+K+"px)",...jT(U.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ie,top:K}},[n,l,U.floating,h.x,h.y]);return f.useMemo(()=>({...h,update:J,refs:ae,elements:U,floatingStyles:te}),[h,J,ae,U,te])}function gx(e){const[t,n]=f.useState(void 0);return Pn(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(o=>{if(!Array.isArray(o)||!o.length)return;const i=o[0];let s,l;if("borderBoxSize"in i){const u=i.borderBoxSize,d=Array.isArray(u)?u[0]:u;s=d.inlineSize,l=d.blockSize}else s=e.offsetWidth,l=e.offsetHeight;n({width:s,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const zT="Popper",[BT,Ns]=An(zT),[cU,UT]=BT(zT),uU=e=>{const{__scopePopper:t,children:n}=e,[r,o]=f.useState(null);return f.createElement(cU,{scope:t,anchor:r,onAnchorChange:o},n)},dU="PopperAnchor",fU=f.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...o}=e,i=UT(dU,n),s=f.useRef(null),l=Be(t,s);return f.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||s.current)}),r?null:f.createElement(Pe.div,Y({},o,{ref:l}))}),VT="PopperContent",[pU,pte]=BT(VT),hU=f.forwardRef((e,t)=>{var n,r,o,i,s,l,u,d;const{__scopePopper:h,side:m="bottom",sideOffset:g=0,align:y="center",alignOffset:x=0,arrowPadding:_=0,avoidCollisions:C=!0,collisionBoundary:S=[],collisionPadding:b=0,sticky:E="partial",hideWhenDetached:k=!1,updatePositionStrategy:P="optimized",onPlaced:M,...A}=e,O=UT(VT,h),[F,V]=f.useState(null),J=Be(t,Kt=>V(Kt)),[G,ae]=f.useState(null),U=gx(G),te=(n=U==null?void 0:U.width)!==null&&n!==void 0?n:0,L=(r=U==null?void 0:U.height)!==null&&r!==void 0?r:0,ie=m+(y!=="center"?"-"+y:""),K=typeof b=="number"?b:{top:0,right:0,bottom:0,left:0,...b},Q=Array.isArray(S)?S:[S],W=Q.length>0,le={padding:K,boundary:Q.filter(mU),altBoundary:W},{refs:ge,floatingStyles:Ve,placement:Ue,isPositioned:We,middlewareData:Me}=lU({strategy:"fixed",placement:ie,whileElementsMounted:(...Kt)=>iU(...Kt,{animationFrame:P==="always"}),elements:{reference:O.anchor},middleware:[FB({mainAxis:g+L,alignmentAxis:x}),C&&jB({mainAxis:!0,crossAxis:!1,limiter:E==="partial"?zB():void 0,...le}),C&&DB({...le}),BB({...le,apply:({elements:Kt,rects:Er,availableWidth:gt,availableHeight:js})=>{const{width:I,height:X}=Er.reference,Z=Kt.floating.style;Z.setProperty("--radix-popper-available-width",`${gt}px`),Z.setProperty("--radix-popper-available-height",`${js}px`),Z.setProperty("--radix-popper-anchor-width",`${I}px`),Z.setProperty("--radix-popper-anchor-height",`${X}px`)}}),G&&aU({element:G,padding:_}),gU({arrowWidth:te,arrowHeight:L}),k&&IB({strategy:"referenceHidden",...le})]}),[fe,xe]=WT(Ue),$e=Ft(M);Pn(()=>{We&&($e==null||$e())},[We,$e]);const Ae=(o=Me.arrow)===null||o===void 0?void 0:o.x,Oe=(i=Me.arrow)===null||i===void 0?void 0:i.y,je=((s=Me.arrow)===null||s===void 0?void 0:s.centerOffset)!==0,[Ot,ct]=f.useState();return Pn(()=>{F&&ct(window.getComputedStyle(F).zIndex)},[F]),f.createElement("div",{ref:ge.setFloating,"data-radix-popper-content-wrapper":"",style:{...Ve,transform:We?Ve.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ot,"--radix-popper-transform-origin":[(l=Me.transformOrigin)===null||l===void 0?void 0:l.x,(u=Me.transformOrigin)===null||u===void 0?void 0:u.y].join(" ")},dir:e.dir},f.createElement(pU,{scope:h,placedSide:fe,onArrowChange:ae,arrowX:Ae,arrowY:Oe,shouldHideArrow:je},f.createElement(Pe.div,Y({"data-side":fe,"data-align":xe},A,{ref:J,style:{...A.style,animation:We?void 0:"none",opacity:(d=Me.hide)!==null&&d!==void 0&&d.referenceHidden?0:void 0}}))))});function mU(e){return e!==null}const gU=e=>({name:"transformOrigin",options:e,fn(t){var n,r,o,i,s;const{placement:l,rects:u,middlewareData:d}=t,m=((n=d.arrow)===null||n===void 0?void 0:n.centerOffset)!==0,g=m?0:e.arrowWidth,y=m?0:e.arrowHeight,[x,_]=WT(l),C={start:"0%",center:"50%",end:"100%"}[_],S=((r=(o=d.arrow)===null||o===void 0?void 0:o.x)!==null&&r!==void 0?r:0)+g/2,b=((i=(s=d.arrow)===null||s===void 0?void 0:s.y)!==null&&i!==void 0?i:0)+y/2;let E="",k="";return x==="bottom"?(E=m?C:`${S}px`,k=`${-y}px`):x==="top"?(E=m?C:`${S}px`,k=`${u.floating.height+y}px`):x==="right"?(E=`${-y}px`,k=m?C:`${b}px`):x==="left"&&(E=`${u.floating.width+y}px`,k=m?C:`${b}px`),{data:{x:E,y:k}}}});function WT(e){const[t,n="center"]=e.split("-");return[t,n]}const Od=uU,zm=fU,Bm=hU,Md=f.forwardRef((e,t)=>{var n;const{container:r=globalThis==null||(n=globalThis.document)===null||n===void 0?void 0:n.body,...o}=e;return r?XI.createPortal(f.createElement(Pe.div,Y({},o,{ref:t})),r):null});function vU(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const bn=e=>{const{present:t,children:n}=e,r=yU(t),o=typeof n=="function"?n({present:r.isPresent}):f.Children.only(n),i=Be(r.ref,o.ref);return typeof n=="function"||r.isPresent?f.cloneElement(o,{ref:i}):null};bn.displayName="Presence";function yU(e){const[t,n]=f.useState(),r=f.useRef({}),o=f.useRef(e),i=f.useRef("none"),s=e?"mounted":"unmounted",[l,u]=vU(s,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return f.useEffect(()=>{const d=sp(r.current);i.current=l==="mounted"?d:"none"},[l]),Pn(()=>{const d=r.current,h=o.current;if(h!==e){const g=i.current,y=sp(d);e?u("MOUNT"):y==="none"||(d==null?void 0:d.display)==="none"?u("UNMOUNT"):u(h&&g!==y?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,u]),Pn(()=>{if(t){const d=m=>{const y=sp(r.current).includes(m.animationName);m.target===t&&y&&Os.flushSync(()=>u("ANIMATION_END"))},h=m=>{m.target===t&&(i.current=sp(r.current))};return t.addEventListener("animationstart",h),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{t.removeEventListener("animationstart",h),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d)}}else u("ANIMATION_END")},[t,u]),{isPresent:["mounted","unmountSuspended"].includes(l),ref:f.useCallback(d=>{d&&(r.current=getComputedStyle(d)),n(d)},[])}}function sp(e){return(e==null?void 0:e.animationName)||"none"}function Zr({prop:e,defaultProp:t,onChange:n=()=>{}}){const[r,o]=wU({defaultProp:t,onChange:n}),i=e!==void 0,s=i?e:r,l=Ft(n),u=f.useCallback(d=>{if(i){const m=typeof d=="function"?d(e):d;m!==e&&l(m)}else o(d)},[i,e,o,l]);return[s,u]}function wU({defaultProp:e,onChange:t}){const n=f.useState(e),[r]=n,o=f.useRef(r),i=Ft(t);return f.useEffect(()=>{o.current!==r&&(i(r),o.current=r)},[r,o,i]),n}const Um=f.forwardRef((e,t)=>f.createElement(Pe.span,Y({},e,{ref:t,style:{position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal",...e.style}}))),xU=Um,[Vm,hte]=An("Tooltip",[Ns]),vx=Ns(),bU="TooltipProvider",_U=700,l1="tooltip.open",[SU,yx]=Vm(bU),EU=e=>{const{__scopeTooltip:t,delayDuration:n=_U,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:i}=e,[s,l]=f.useState(!0),u=f.useRef(!1),d=f.useRef(0);return f.useEffect(()=>{const h=d.current;return()=>window.clearTimeout(h)},[]),f.createElement(SU,{scope:t,isOpenDelayed:s,delayDuration:n,onOpen:f.useCallback(()=>{window.clearTimeout(d.current),l(!1)},[]),onClose:f.useCallback(()=>{window.clearTimeout(d.current),d.current=window.setTimeout(()=>l(!0),r)},[r]),isPointerInTransitRef:u,onPointerInTransitChange:f.useCallback(h=>{u.current=h},[]),disableHoverableContent:o},i)},wx="Tooltip",[CU,Wm]=Vm(wx),$U=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o=!1,onOpenChange:i,disableHoverableContent:s,delayDuration:l}=e,u=yx(wx,e.__scopeTooltip),d=vx(t),[h,m]=f.useState(null),g=nr(),y=f.useRef(0),x=s??u.disableHoverableContent,_=l??u.delayDuration,C=f.useRef(!1),[S=!1,b]=Zr({prop:r,defaultProp:o,onChange:A=>{A?(u.onOpen(),document.dispatchEvent(new CustomEvent(l1))):u.onClose(),i==null||i(A)}}),E=f.useMemo(()=>S?C.current?"delayed-open":"instant-open":"closed",[S]),k=f.useCallback(()=>{window.clearTimeout(y.current),C.current=!1,b(!0)},[b]),P=f.useCallback(()=>{window.clearTimeout(y.current),b(!1)},[b]),M=f.useCallback(()=>{window.clearTimeout(y.current),y.current=window.setTimeout(()=>{C.current=!0,b(!0)},_)},[_,b]);return f.useEffect(()=>()=>window.clearTimeout(y.current),[]),f.createElement(Od,d,f.createElement(CU,{scope:t,contentId:g,open:S,stateAttribute:E,trigger:h,onTriggerChange:m,onTriggerEnter:f.useCallback(()=>{u.isOpenDelayed?M():k()},[u.isOpenDelayed,M,k]),onTriggerLeave:f.useCallback(()=>{x?P():window.clearTimeout(y.current)},[P,x]),onOpen:k,onClose:P,disableHoverableContent:x},n))},UC="TooltipTrigger",kU=f.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=Wm(UC,n),i=yx(UC,n),s=vx(n),l=f.useRef(null),u=Be(t,l,o.onTriggerChange),d=f.useRef(!1),h=f.useRef(!1),m=f.useCallback(()=>d.current=!1,[]);return f.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),f.createElement(zm,Y({asChild:!0},s),f.createElement(Pe.button,Y({"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute},r,{ref:u,onPointerMove:ue(e.onPointerMove,g=>{g.pointerType!=="touch"&&!h.current&&!i.isPointerInTransitRef.current&&(o.onTriggerEnter(),h.current=!0)}),onPointerLeave:ue(e.onPointerLeave,()=>{o.onTriggerLeave(),h.current=!1}),onPointerDown:ue(e.onPointerDown,()=>{d.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ue(e.onFocus,()=>{d.current||o.onOpen()}),onBlur:ue(e.onBlur,o.onClose),onClick:ue(e.onClick,o.onClose)})))}),RU="TooltipPortal",[mte,TU]=Vm(RU,{forceMount:void 0}),rd="TooltipContent",PU=f.forwardRef((e,t)=>{const n=TU(rd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...i}=e,s=Wm(rd,e.__scopeTooltip);return f.createElement(bn,{present:r||s.open},s.disableHoverableContent?f.createElement(HT,Y({side:o},i,{ref:t})):f.createElement(AU,Y({side:o},i,{ref:t})))}),AU=f.forwardRef((e,t)=>{const n=Wm(rd,e.__scopeTooltip),r=yx(rd,e.__scopeTooltip),o=f.useRef(null),i=Be(t,o),[s,l]=f.useState(null),{trigger:u,onClose:d}=n,h=o.current,{onPointerInTransitChange:m}=r,g=f.useCallback(()=>{l(null),m(!1)},[m]),y=f.useCallback((x,_)=>{const C=x.currentTarget,S={x:x.clientX,y:x.clientY},b=MU(S,C.getBoundingClientRect()),E=NU(S,b),k=DU(_.getBoundingClientRect()),P=LU([...E,...k]);l(P),m(!0)},[m]);return f.useEffect(()=>()=>g(),[g]),f.useEffect(()=>{if(u&&h){const x=C=>y(C,h),_=C=>y(C,u);return u.addEventListener("pointerleave",x),h.addEventListener("pointerleave",_),()=>{u.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",_)}}},[u,h,y,g]),f.useEffect(()=>{if(s){const x=_=>{const C=_.target,S={x:_.clientX,y:_.clientY},b=(u==null?void 0:u.contains(C))||(h==null?void 0:h.contains(C)),E=!IU(S,s);b?g():E&&(g(),d())};return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[u,h,s,d,g]),f.createElement(HT,Y({},e,{ref:i}))}),[OU,gte]=Vm(wx,{isInside:!1}),HT=f.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:i,onPointerDownOutside:s,...l}=e,u=Wm(rd,n),d=vx(n),{onClose:h}=u;return f.useEffect(()=>(document.addEventListener(l1,h),()=>document.removeEventListener(l1,h)),[h]),f.useEffect(()=>{if(u.trigger){const m=g=>{const y=g.target;y!=null&&y.contains(u.trigger)&&h()};return window.addEventListener("scroll",m,{capture:!0}),()=>window.removeEventListener("scroll",m,{capture:!0})}},[u.trigger,h]),f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:m=>m.preventDefault(),onDismiss:h},f.createElement(Bm,Y({"data-state":u.stateAttribute},d,l,{ref:t,style:{...l.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)"}}),f.createElement(sx,null,r),f.createElement(OU,{scope:n,isInside:!0},f.createElement(xU,{id:u.contentId,role:"tooltip"},o||r))))});function MU(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),i=Math.abs(t.left-e.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 NU(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function DU(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function IU(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function LU(e){const t=e.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),FU(t)}function FU(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],s=t[t.length-2];if((i.x-s.x)*(o.y-s.y)>=(i.y-s.y)*(o.x-s.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const 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(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}const jU=EU,zU=$U,BU=kU,KT=PU,UU=jU,YT=zU,GT=BU,xx=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(KT,{ref:r,sideOffset:t,className:Ce("z-50 border overflow-hidden rounded-md bg-background text-foreground px-3 py-1.5 text-xs animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));xx.displayName=KT.displayName;const bx=Om("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground shadow hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",outline:"border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),yn=f.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},i)=>{const s=r?Wo:"button";return v.jsx(s,{className:Ce(bx({variant:t,size:n,className:e}),"outline-none cursor-default"),ref:i,tabIndex:-1,...o})});yn.displayName="Button";const vn=f.forwardRef(({tooltip:e,children:t,...n},r)=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(yn,{variant:"ghost",size:"icon",...n,ref:r,tabIndex:-1,className:"cursor-default bg-background",children:v.jsx("div",{className:"icon-button-icon-wrapper",children:t})})}),v.jsx(xx,{children:v.jsx("p",{children:e})})]})),c1=e=>{const{onFileUpload:t,children:n,...r}=e,[o]=f.useState(`file-upload-${Math.random().toString()}`),i=s=>{var u;const l=(u=s.currentTarget.files)==null?void 0:u[0];l&&t(l)};return v.jsxs(v.Fragment,{children:[v.jsx("label",{htmlFor:o,children:v.jsx(vn,{...r,asChild:!0,children:n})}),v.jsx(Pd,{style:{display:"none"},id:o,name:o,type:"file",onChange:i,accept:"image/png, image/jpeg"})]})};var VU={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"};const WU=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jt=(e,t)=>{const n=f.forwardRef(({color:r="currentColor",size:o=24,strokeWidth:i=2,absoluteStrokeWidth:s,children:l,...u},d)=>f.createElement("svg",{ref:d,...VU,width:o,height:o,stroke:r,strokeWidth:s?Number(i)*24/Number(o):i,className:`lucide lucide-${WU(e)}`,...u},[...t.map(([h,m])=>f.createElement(h,m)),...(Array.isArray(l)?l:[l])||[]]));return n.displayName=`${e}`,n},HU=Jt("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]),KU=Jt("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),YU=Jt("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),GU=Jt("Coffee",[["path",{d:"M17 8h1a4 4 0 1 1 0 8h-1",key:"jx4kbh"}],["path",{d:"M3 8h14v9a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4Z",key:"1bxrl0"}],["line",{x1:"6",x2:"6",y1:"2",y2:"4",key:"1cr9l3"}],["line",{x1:"10",x2:"10",y1:"2",y2:"4",key:"170wym"}],["line",{x1:"14",x2:"14",y1:"2",y2:"4",key:"1c5f70"}]]),XU=Jt("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"}]]),ZU=Jt("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]),qU=Jt("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]),QU=Jt("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),JU=Jt("FolderClosed",[["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"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]),XT=Jt("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]),eV=Jt("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"}]]),tV=Jt("Keyboard",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",ry:"2",key:"15u882"}],["path",{d:"M6 8h.001",key:"1ej0i3"}],["path",{d:"M10 8h.001",key:"1x2st2"}],["path",{d:"M14 8h.001",key:"1vkmyp"}],["path",{d:"M18 8h.001",key:"kfsenl"}],["path",{d:"M8 12h.001",key:"1sjpby"}],["path",{d:"M12 12h.001",key:"al75ts"}],["path",{d:"M16 12h.001",key:"931bgk"}],["path",{d:"M7 16h10",key:"wp8him"}]]),nV=Jt("MousePointerClick",[["path",{d:"m9 9 5 12 1.8-5.2L21 14Z",key:"1b76lo"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}]]),rV=Jt("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]),oV=Jt("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"}]]),iV=Jt("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"}]]),VC=Jt("Slice",[["path",{d:"m8 14-6 6h9v-3",key:"zo3j9a"}],["path",{d:"M18.37 3.63 8 14l3 3L21.37 6.63a2.12 2.12 0 1 0-3-3Z",key:"1dzx0j"}]]),WC=Jt("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]),sV=Jt("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]),ZT=Jt("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);function aV(e,t){const[n,r]=f.useState(e);return f.useEffect(()=>{const o=setTimeout(()=>{r(e)},t);return()=>{clearTimeout(o)}},[e,t]),n}function u1(e){const[t,n]=f.useState(()=>typeof e=="boolean"?e:!!e),r=f.useCallback(o=>n(typeof o=="boolean"?o:i=>!i),[]);return[t,r]}const w0="focusScope.autoFocusOnMount",x0="focusScope.autoFocusOnUnmount",HC={bubbles:!1,cancelable:!0},Hm=f.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:i,...s}=e,[l,u]=f.useState(null),d=Ft(o),h=Ft(i),m=f.useRef(null),g=Be(t,_=>u(_)),y=f.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;f.useEffect(()=>{if(r){let b=function(M){if(y.paused||!l)return;const A=M.target;l.contains(A)?m.current=A:Hi(m.current,{select:!0})},E=function(M){if(y.paused||!l)return;const A=M.relatedTarget;A!==null&&(l.contains(A)||Hi(m.current,{select:!0}))},k=function(M){if(document.activeElement===document.body)for(const O of M)O.removedNodes.length>0&&Hi(l)};var _=b,C=E,S=k;document.addEventListener("focusin",b),document.addEventListener("focusout",E);const P=new MutationObserver(k);return l&&P.observe(l,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",b),document.removeEventListener("focusout",E),P.disconnect()}}},[r,l,y.paused]),f.useEffect(()=>{if(l){YC.add(y);const _=document.activeElement;if(!l.contains(_)){const S=new CustomEvent(w0,HC);l.addEventListener(w0,d),l.dispatchEvent(S),S.defaultPrevented||(lV(pV(qT(l)),{select:!0}),document.activeElement===_&&Hi(l))}return()=>{l.removeEventListener(w0,d),setTimeout(()=>{const S=new CustomEvent(x0,HC);l.addEventListener(x0,h),l.dispatchEvent(S),S.defaultPrevented||Hi(_??document.body,{select:!0}),l.removeEventListener(x0,h),YC.remove(y)},0)}}},[l,d,h,y]);const x=f.useCallback(_=>{if(!n&&!r||y.paused)return;const C=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,S=document.activeElement;if(C&&S){const b=_.currentTarget,[E,k]=cV(b);E&&k?!_.shiftKey&&S===k?(_.preventDefault(),n&&Hi(E,{select:!0})):_.shiftKey&&S===E&&(_.preventDefault(),n&&Hi(k,{select:!0})):S===b&&_.preventDefault()}},[n,r,y.paused]);return f.createElement(Pe.div,Y({tabIndex:-1},s,{ref:g,onKeyDown:x}))});function lV(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Hi(r,{select:t}),document.activeElement!==n)return}function cV(e){const t=qT(e),n=KC(t,e),r=KC(t.reverse(),e);return[n,r]}function qT(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function KC(e,t){for(const n of e)if(!uV(n,{upTo:t}))return n}function uV(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function dV(e){return e instanceof HTMLInputElement&&"select"in e}function Hi(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&dV(e)&&t&&e.select()}}const YC=fV();function fV(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=GC(e,t),e.unshift(t)},remove(t){var n;e=GC(e,t),(n=e[0])===null||n===void 0||n.resume()}}}function GC(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function pV(e){return e.filter(t=>t.tagName!=="A")}let b0=0;function Km(){f.useEffect(()=>{var e,t;const n=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",(e=n[0])!==null&&e!==void 0?e:XC()),document.body.insertAdjacentElement("beforeend",(t=n[1])!==null&&t!==void 0?t:XC()),b0++,()=>{b0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(r=>r.remove()),b0--}},[])}function XC(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.cssText="outline: none; opacity: 0; position: fixed; pointer-events: none",e}var Mo=function(){return Mo=Object.assign||function(t){for(var n,r=1,o=arguments.length;r"u")return PV;var t=AV(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},MV=tP(),NV=function(e,t,n,r){var o=e.left,i=e.top,s=e.right,l=e.gap;return n===void 0&&(n="margin"),` + .`.concat(mV,` { + overflow: hidden `).concat(r,`; + padding-right: `).concat(l,"px ").concat(r,`; + } + body { + overflow: hidden `).concat(r,`; + overscroll-behavior: contain; + `).concat([t&&"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(l,"px ").concat(r,`; + `),n==="padding"&&"padding-right: ".concat(l,"px ").concat(r,";")].filter(Boolean).join(""),` + } + + .`).concat(Wp,` { + right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Hp,` { + margin-right: `).concat(l,"px ").concat(r,`; + } + + .`).concat(Wp," .").concat(Wp,` { + right: 0 `).concat(r,`; + } + + .`).concat(Hp," .").concat(Hp,` { + margin-right: 0 `).concat(r,`; + } + + body { + `).concat(gV,": ").concat(l,`px; + } +`)},DV=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,o=r===void 0?"margin":r,i=f.useMemo(function(){return OV(o)},[o]);return f.createElement(MV,{styles:NV(i,!t,o,n?"":"!important")})},d1=!1;if(typeof window<"u")try{var ap=Object.defineProperty({},"passive",{get:function(){return d1=!0,!0}});window.addEventListener("test",ap,ap),window.removeEventListener("test",ap,ap)}catch{d1=!1}var qa=d1?{passive:!1}:!1,IV=function(e){return e.tagName==="TEXTAREA"},nP=function(e,t){var n=window.getComputedStyle(e);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!IV(e)&&n[t]==="visible")},LV=function(e){return nP(e,"overflowY")},FV=function(e){return nP(e,"overflowX")},qC=function(e,t){var n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var r=rP(e,n);if(r){var o=oP(e,n),i=o[1],s=o[2];if(i>s)return!0}n=n.parentNode}while(n&&n!==document.body);return!1},jV=function(e){var t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return[t,n,r]},zV=function(e){var t=e.scrollLeft,n=e.scrollWidth,r=e.clientWidth;return[t,n,r]},rP=function(e,t){return e==="v"?LV(t):FV(t)},oP=function(e,t){return e==="v"?jV(t):zV(t)},BV=function(e,t){return e==="h"&&t==="rtl"?-1:1},UV=function(e,t,n,r,o){var i=BV(e,window.getComputedStyle(t).direction),s=i*r,l=n.target,u=t.contains(l),d=!1,h=s>0,m=0,g=0;do{var y=oP(e,l),x=y[0],_=y[1],C=y[2],S=_-C-i*x;(x||S)&&rP(e,l)&&(m+=S,g+=x),l=l.parentNode}while(!u&&l!==document.body||u&&(t.contains(l)||t===l));return(h&&(o&&m===0||!o&&s>m)||!h&&(o&&g===0||!o&&-s>g))&&(d=!0),d},lp=function(e){return"changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},QC=function(e){return[e.deltaX,e.deltaY]},JC=function(e){return e&&"current"in e?e.current:e},VV=function(e,t){return e[0]===t[0]&&e[1]===t[1]},WV=function(e){return` + .block-interactivity-`.concat(e,` {pointer-events: none;} + .allow-interactivity-`).concat(e,` {pointer-events: all;} +`)},HV=0,Qa=[];function KV(e){var t=f.useRef([]),n=f.useRef([0,0]),r=f.useRef(),o=f.useState(HV++)[0],i=f.useState(function(){return tP()})[0],s=f.useRef(e);f.useEffect(function(){s.current=e},[e]),f.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var _=hV([e.lockRef.current],(e.shards||[]).map(JC),!0).filter(Boolean);return _.forEach(function(C){return C.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),_.forEach(function(C){return C.classList.remove("allow-interactivity-".concat(o))})}}},[e.inert,e.lockRef.current,e.shards]);var l=f.useCallback(function(_,C){if("touches"in _&&_.touches.length===2)return!s.current.allowPinchZoom;var S=lp(_),b=n.current,E="deltaX"in _?_.deltaX:b[0]-S[0],k="deltaY"in _?_.deltaY:b[1]-S[1],P,M=_.target,A=Math.abs(E)>Math.abs(k)?"h":"v";if("touches"in _&&A==="h"&&M.type==="range")return!1;var O=qC(A,M);if(!O)return!0;if(O?P=A:(P=A==="v"?"h":"v",O=qC(A,M)),!O)return!1;if(!r.current&&"changedTouches"in _&&(E||k)&&(r.current=P),!P)return!0;var F=r.current||P;return UV(F,C,_,F==="h"?E:k,!0)},[]),u=f.useCallback(function(_){var C=_;if(!(!Qa.length||Qa[Qa.length-1]!==i)){var S="deltaY"in C?QC(C):lp(C),b=t.current.filter(function(P){return P.name===C.type&&P.target===C.target&&VV(P.delta,S)})[0];if(b&&b.should){C.cancelable&&C.preventDefault();return}if(!b){var E=(s.current.shards||[]).map(JC).filter(Boolean).filter(function(P){return P.contains(C.target)}),k=E.length>0?l(C,E[0]):!s.current.noIsolation;k&&C.cancelable&&C.preventDefault()}}},[]),d=f.useCallback(function(_,C,S,b){var E={name:_,delta:C,target:S,should:b};t.current.push(E),setTimeout(function(){t.current=t.current.filter(function(k){return k!==E})},1)},[]),h=f.useCallback(function(_){n.current=lp(_),r.current=void 0},[]),m=f.useCallback(function(_){d(_.type,QC(_),_.target,l(_,e.lockRef.current))},[]),g=f.useCallback(function(_){d(_.type,lp(_),_.target,l(_,e.lockRef.current))},[]);f.useEffect(function(){return Qa.push(i),e.setCallbacks({onScrollCapture:m,onWheelCapture:m,onTouchMoveCapture:g}),document.addEventListener("wheel",u,qa),document.addEventListener("touchmove",u,qa),document.addEventListener("touchstart",h,qa),function(){Qa=Qa.filter(function(_){return _!==i}),document.removeEventListener("wheel",u,qa),document.removeEventListener("touchmove",u,qa),document.removeEventListener("touchstart",h,qa)}},[]);var y=e.removeScrollBar,x=e.inert;return f.createElement(f.Fragment,null,x?f.createElement(i,{styles:WV(o)}):null,y?f.createElement(DV,{gapMode:"margin"}):null)}const YV=SV(eP,KV);var iP=f.forwardRef(function(e,t){return f.createElement(Ym,Mo({},e,{ref:t,sideCar:YV}))});iP.classNames=Ym.classNames;const Gm=iP;var GV=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},Ja=new WeakMap,cp=new WeakMap,up={},E0=0,sP=function(e){return e&&(e.host||sP(e.parentNode))},XV=function(e,t){return t.map(function(n){if(e.contains(n))return n;var r=sP(n);return r&&e.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",e,". Doing nothing"),null)}).filter(function(n){return!!n})},ZV=function(e,t,n,r){var o=XV(t,Array.isArray(e)?e:[e]);up[n]||(up[n]=new WeakMap);var i=up[n],s=[],l=new Set,u=new Set(o),d=function(m){!m||l.has(m)||(l.add(m),d(m.parentNode))};o.forEach(d);var h=function(m){!m||u.has(m)||Array.prototype.forEach.call(m.children,function(g){if(l.has(g))h(g);else{var y=g.getAttribute(r),x=y!==null&&y!=="false",_=(Ja.get(g)||0)+1,C=(i.get(g)||0)+1;Ja.set(g,_),i.set(g,C),s.push(g),_===1&&x&&cp.set(g,!0),C===1&&g.setAttribute(n,"true"),x||g.setAttribute(r,"true")}})};return h(t),l.clear(),E0++,function(){s.forEach(function(m){var g=Ja.get(m)-1,y=i.get(m)-1;Ja.set(m,g),i.set(m,y),g||(cp.has(m)||m.removeAttribute(r),cp.delete(m)),y||m.removeAttribute(n)}),E0--,E0||(Ja=new WeakMap,Ja=new WeakMap,cp=new WeakMap,up={})}},Xm=function(e,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(e)?e:[e]),o=t||GV(e);return o?(r.push.apply(r,Array.from(o.querySelectorAll("[aria-live]"))),ZV(r,o,n,"aria-hidden")):function(){return null}};const aP="Dialog",[lP,cP]=An(aP),[qV,bo]=lP(aP),QV=e=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!0}=e,l=f.useRef(null),u=f.useRef(null),[d=!1,h]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(qV,{scope:t,triggerRef:l,contentRef:u,contentId:nr(),titleId:nr(),descriptionId:nr(),open:d,onOpenChange:h,onOpenToggle:f.useCallback(()=>h(m=>!m),[h]),modal:s},n)},JV="DialogTrigger",uP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(JV,n),i=Be(t,o.triggerRef);return f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":_x(o.open)},r,{ref:i,onClick:ue(e.onClick,o.onOpenToggle)}))}),dP="DialogPortal",[eW,fP]=lP(dP,{forceMount:void 0}),tW=e=>{const{__scopeDialog:t,forceMount:n,children:r,container:o}=e,i=bo(dP,t);return f.createElement(eW,{scope:t,forceMount:n},f.Children.map(r,s=>f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},s))))},f1="DialogOverlay",nW=f.forwardRef((e,t)=>{const n=fP(f1,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(f1,e.__scopeDialog);return i.modal?f.createElement(bn,{present:r||i.open},f.createElement(rW,Y({},o,{ref:t}))):null}),rW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(f1,n);return f.createElement(Gm,{as:Wo,allowPinchZoom:!0,shards:[o.contentRef]},f.createElement(Pe.div,Y({"data-state":_x(o.open)},r,{ref:t,style:{pointerEvents:"auto",...r.style}})))}),oc="DialogContent",oW=f.forwardRef((e,t)=>{const n=fP(oc,e.__scopeDialog),{forceMount:r=n.forceMount,...o}=e,i=bo(oc,e.__scopeDialog);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(iW,Y({},o,{ref:t})):f.createElement(sW,Y({},o,{ref:t})))}),iW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(null),o=Be(t,n.contentRef,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(pP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,i=>{var s;i.preventDefault(),(s=n.triggerRef.current)===null||s===void 0||s.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,i=>{const s=i.detail.originalEvent,l=s.button===0&&s.ctrlKey===!0;(s.button===2||l)&&i.preventDefault()}),onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault())}))}),sW=f.forwardRef((e,t)=>{const n=bo(oc,e.__scopeDialog),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(pP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),pP=f.forwardRef((e,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,...s}=e,l=bo(oc,n),u=f.useRef(null),d=Be(t,u);return Km(),f.createElement(f.Fragment,null,f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,Y({role:"dialog",id:l.contentId,"aria-describedby":l.descriptionId,"aria-labelledby":l.titleId,"data-state":_x(l.open)},s,{ref:d,onDismiss:()=>l.onOpenChange(!1)}))),!1)}),hP="DialogTitle",aW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(hP,n);return f.createElement(Pe.h2,Y({id:o.titleId},r,{ref:t}))}),lW="DialogDescription",mP=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(lW,n);return f.createElement(Pe.p,Y({id:o.descriptionId},r,{ref:t}))}),cW="DialogClose",uW=f.forwardRef((e,t)=>{const{__scopeDialog:n,...r}=e,o=bo(cW,n);return f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,()=>o.onOpenChange(!1))}))});function _x(e){return e?"open":"closed"}const dW="DialogTitleWarning",[fW,vte]=pB(dW,{contentName:oc,titleName:hP,docsSlug:"dialog"}),Sx=QV,gP=uP,Ex=tW,Nd=nW,Dd=oW,Id=aW,Ld=mP,Cx=uW,Zm=Sx,$x=gP,pW=Ex,vP=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{ref:n,className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t}));vP.displayName=Nd.displayName;const Fd=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(pW,{children:[v.jsx(vP,{}),v.jsxs(Dd,{ref:r,className:Ce("fixed left-[50%] top-[50%] z-50 flex flex-col w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e,"outline-none"),onCloseAutoFocus:o=>o.preventDefault(),...n,children:[t,v.jsxs(Cx,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",children:[v.jsx(yT,{className:"h-4 w-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Fd.displayName=Dd.displayName;const yP=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-1.5 text-center sm:text-left",e),...t});yP.displayName="DialogHeader";const jd=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-2xl font-semibold leading-none tracking-tight",e),...t}));jd.displayName=Id.displayName;const hW=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));hW.displayName=Ld.displayName;function p1(){return p1=Object.assign?Object.assign.bind():function(e){for(var t=1;t'),!0):t?e.some(function(n){return t.includes(n)})||e.includes("*"):!0}var _W=function(t,n,r){r===void 0&&(r=!1);var o=n.alt,i=n.meta,s=n.mod,l=n.shift,u=n.ctrl,d=n.keys,h=t.key,m=t.code,g=t.ctrlKey,y=t.metaKey,x=t.shiftKey,_=t.altKey,C=ss(m),S=h.toLowerCase();if(!r){if(o===!_&&S!=="alt"||l===!x&&S!=="shift")return!1;if(s){if(!y&&!g)return!1}else if(i===!y&&S!=="meta"&&S!=="os"||u===!g&&S!=="ctrl"&&S!=="control")return!1}return d&&d.length===1&&(d.includes(S)||d.includes(C))?!0:d?vW(d):!d},SW=f.createContext(void 0),EW=function(){return f.useContext(SW)};function SP(e,t){return e&&t&&typeof e=="object"&&typeof t=="object"?Object.keys(e).length===Object.keys(t).length&&Object.keys(e).reduce(function(n,r){return n&&SP(e[r],t[r])},!0):e===t}var CW=f.createContext({hotkeys:[],enabledScopes:[],toggleScope:function(){},enableScope:function(){},disableScope:function(){}}),$W=function(){return f.useContext(CW)};function kW(e){var t=f.useRef(void 0);return SP(t.current,e)||(t.current=e),t.current}var e2=function(t){t.stopPropagation(),t.preventDefault(),t.stopImmediatePropagation()},RW=typeof window<"u"?f.useLayoutEffect:f.useEffect;function TW(e,t,n,r){var o=f.useRef(null),i=f.useRef(!1),s=n instanceof Array?r instanceof Array?void 0:r:n,l=kx(e)?e.join(s==null?void 0:s.splitKey):e,u=n instanceof Array?n:r instanceof Array?r:void 0,d=f.useCallback(t,u??[]),h=f.useRef(d);u?h.current=d:h.current=t;var m=kW(s),g=$W(),y=g.enabledScopes,x=EW();return RW(function(){if(!((m==null?void 0:m.enabled)===!1||!bW(y,m==null?void 0:m.scopes))){var _=function(k,P){var M;if(P===void 0&&(P=!1),!(xW(k)&&!_P(k,m==null?void 0:m.enableOnFormTags))&&!(m!=null&&m.ignoreEventWhen!=null&&m.ignoreEventWhen(k))){if(o.current!==null&&document.activeElement!==o.current&&!o.current.contains(document.activeElement)){e2(k);return}(M=k.target)!=null&&M.isContentEditable&&!(m!=null&&m.enableOnContentEditable)||C0(l,m==null?void 0:m.splitKey).forEach(function(A){var O,F=$0(A,m==null?void 0:m.combinationKey);if(_W(k,F,m==null?void 0:m.ignoreModifiers)||(O=F.keys)!=null&&O.includes("*")){if(P&&i.current)return;if(yW(k,F,m==null?void 0:m.preventDefault),!wW(k,F,m==null?void 0:m.enabled)){e2(k);return}h.current(k,F),P||(i.current=!0)}})}},C=function(k){k.key!==void 0&&(xP(ss(k.code)),((m==null?void 0:m.keydown)===void 0&&(m==null?void 0:m.keyup)!==!0||m!=null&&m.keydown)&&_(k))},S=function(k){k.key!==void 0&&(bP(ss(k.code)),i.current=!1,m!=null&&m.keyup&&_(k,!0))},b=o.current||(s==null?void 0:s.document)||document;return b.addEventListener("keyup",S),b.addEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.addHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))}),function(){b.removeEventListener("keyup",S),b.removeEventListener("keydown",C),x&&C0(l,m==null?void 0:m.splitKey).forEach(function(E){return x.removeHotkey($0(E,m==null?void 0:m.combinationKey,m==null?void 0:m.description))})}}},[l,m,y]),o}const Zn=(e,t,n)=>{const r=bt(i=>i.disableShortCuts);return TW(e,t,{enabled:!r},n)};function ur(e){const{content:t,keys:n}=e;return v.jsxs("div",{className:"flex justify-between",children:[v.jsx("div",{children:t}),v.jsx("div",{className:"flex gap-[8px]",children:n.map(r=>v.jsx("div",{className:"border px-2 py-1 rounded-lg",children:r},r))})]})}const PW=function(){return/macintosh|mac os x/i.test(navigator.userAgent)},dp=()=>PW()?"Cmd":"Ctrl";function AW(){const[e,t]=u1(!1);return Zn("h",()=>{t()}),v.jsxs(Zm,{open:e,onOpenChange:t,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Hotkeys",children:v.jsx(tV,{})})}),v.jsx(Fd,{children:v.jsxs(yP,{children:[v.jsx(jd,{children:"Hotkeys"}),v.jsxs("div",{className:"flex gap-2 flex-col pt-4",children:[v.jsx(ur,{content:"Pan",keys:["Space + Drag"]}),v.jsx(ur,{content:"Reset Zoom/Pan",keys:["Esc"]}),v.jsx(ur,{content:"Decrease Brush Size",keys:["["]}),v.jsx(ur,{content:"Increase Brush Size",keys:["]"]}),v.jsx(ur,{content:"View Original Image",keys:["Hold Tab"]}),v.jsx(ur,{content:"Undo",keys:[dp(),"Z"]}),v.jsx(ur,{content:"Redo",keys:[dp(),"Shift","Z"]}),v.jsx(ur,{content:"Copy Result",keys:[dp(),"C"]}),v.jsx(ur,{content:"Paste Image",keys:[dp(),"V"]}),v.jsx(ur,{content:"Trigger Manually Inpainting",keys:["Shift","R"]}),v.jsx(ur,{content:"Toggle Hotkeys Dialog",keys:["H"]}),v.jsx(ur,{content:"Toggle Settings Dialog",keys:["S"]}),v.jsx(ur,{content:"Toggle File Manager",keys:["F"]})]})]})})]})}function Rx(e){const[t]=f.useState(new Image),[n,r]=f.useState(!1);return f.useEffect(()=>{if(e)return t.onload=()=>{r(!0)},r(!1),t.src=URL.createObjectURL(e),()=>{t.onload=null}},[e,t]),[t,n]}const EP="Popover",[CP,yte]=An(EP,[Ns]),Tx=Ns(),[OW,bc]=CP(EP),MW=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:o,onOpenChange:i,modal:s=!1}=e,l=Tx(t),u=f.useRef(null),[d,h]=f.useState(!1),[m=!1,g]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(Od,l,f.createElement(OW,{scope:t,contentId:nr(),triggerRef:u,open:m,onOpenChange:g,onOpenToggle:f.useCallback(()=>g(y=>!y),[g]),hasCustomAnchor:d,onCustomAnchorAdd:f.useCallback(()=>h(!0),[]),onCustomAnchorRemove:f.useCallback(()=>h(!1),[]),modal:s},n))},NW="PopoverTrigger",DW=f.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,o=bc(NW,n),i=Tx(n),s=Be(t,o.triggerRef),l=f.createElement(Pe.button,Y({type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":RP(o.open)},r,{ref:s,onClick:ue(e.onClick,o.onOpenToggle)}));return o.hasCustomAnchor?l:f.createElement(zm,Y({asChild:!0},i),l)}),$P="PopoverPortal",[IW,LW]=CP($P,{forceMount:void 0}),FW=e=>{const{__scopePopover:t,forceMount:n,children:r,container:o}=e,i=bc($P,t);return f.createElement(IW,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},od="PopoverContent",jW=f.forwardRef((e,t)=>{const n=LW(od,e.__scopePopover),{forceMount:r=n.forceMount,...o}=e,i=bc(od,e.__scopePopover);return f.createElement(bn,{present:r||i.open},i.modal?f.createElement(zW,Y({},o,{ref:t})):f.createElement(BW,Y({},o,{ref:t})))}),zW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(null),o=Be(t,r),i=f.useRef(!1);return f.useEffect(()=>{const s=r.current;if(s)return Xm(s)},[]),f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(kP,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ue(e.onCloseAutoFocus,s=>{var l;s.preventDefault(),i.current||(l=n.triggerRef.current)===null||l===void 0||l.focus()}),onPointerDownOutside:ue(e.onPointerDownOutside,s=>{const l=s.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;i.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:ue(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1})})))}),BW=f.forwardRef((e,t)=>{const n=bc(od,e.__scopePopover),r=f.useRef(!1),o=f.useRef(!1);return f.createElement(kP,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var s;if((s=e.onCloseAutoFocus)===null||s===void 0||s.call(e,i),!i.defaultPrevented){var l;r.current||(l=n.triggerRef.current)===null||l===void 0||l.focus(),i.preventDefault()}r.current=!1,o.current=!1},onInteractOutside:i=>{var s,l;(s=e.onInteractOutside)===null||s===void 0||s.call(e,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(o.current=!0));const u=i.target;((l=n.triggerRef.current)===null||l===void 0?void 0:l.contains(u))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&o.current&&i.preventDefault()}}))}),kP=f.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:o,onCloseAutoFocus:i,disableOutsidePointerEvents:s,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:h,...m}=e,g=bc(od,n),y=Tx(n);return Km(),f.createElement(Hm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:o,onUnmountAutoFocus:i},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:s,onInteractOutside:h,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>g.onOpenChange(!1)},f.createElement(Bm,Y({"data-state":RP(g.open),role:"dialog",id:g.contentId},y,m,{ref:t,style:{...m.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)"}}))))});function RP(e){return e?"open":"closed"}const UW=MW,VW=DW,WW=FW,TP=jW,HW=UW,KW=VW,PP=f.forwardRef(({className:e,align:t="center",sideOffset:n=4,...r},o)=>v.jsx(WW,{children:v.jsx(TP,{ref:o,align:t,tabIndex:-1,sideOffset:n,className:Ce("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...r})}));PP.displayName=TP.displayName;function YW(){var e=f.useRef(!0);return e.current?(e.current=!1,!0):e.current}var GW=function(e,t){var n=YW();f.useEffect(function(){if(!n)return e()},t)};const XW=GW;var ZW=function(){};function Px(e){for(var t=[],n=1;n{const[e,t,n,r,o,i]=bt(g=>[g.getIsProcessing(),g.settings.prompt,g.updateSettings,g.runInpainting,g.showPrevMask,g.hidePrevMask]),s=f.useRef(null);OP(s,()=>{s!=null&&s.current&&s.current.blur()});const l=g=>{g.preventDefault(),g.stopPropagation();const y=g.target;n({prompt:y.value})},u=()=>{e||r()},d=g=>{g.key==="Enter"&&!e&&u()},h=()=>{o()},m=()=>{i()};return v.jsxs("div",{className:"flex gap-4 items-center",children:[v.jsx(Pd,{ref:s,className:"min-w-[500px]",value:t,onInput:l,onKeyUp:d,placeholder:"I want to repaint of..."}),v.jsx(yn,{size:"sm",onClick:u,disabled:e,onMouseEnter:h,onMouseLeave:m,children:"Paint"})]})};var Lh={exports:{}};/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */Lh.exports;(function(e,t){(function(){var n,r="4.17.21",o=200,i="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",s="Expected a function",l="Invalid `variable` option passed into `_.template`",u="__lodash_hash_undefined__",d=500,h="__lodash_placeholder__",m=1,g=2,y=4,x=1,_=2,C=1,S=2,b=4,E=8,k=16,P=32,M=64,A=128,O=256,F=512,V=30,J="...",G=800,ae=16,U=1,te=2,L=3,ie=1/0,K=9007199254740991,Q=17976931348623157e292,W=NaN,le=4294967295,ge=le-1,Ve=le>>>1,Ue=[["ary",A],["bind",C],["bindKey",S],["curry",E],["curryRight",k],["flip",F],["partial",P],["partialRight",M],["rearg",O]],We="[object Arguments]",Me="[object Array]",fe="[object AsyncFunction]",xe="[object Boolean]",$e="[object Date]",Ae="[object DOMException]",Oe="[object Error]",je="[object Function]",Ot="[object GeneratorFunction]",ct="[object Map]",Kt="[object Number]",Er="[object Null]",gt="[object Object]",js="[object Promise]",I="[object Proxy]",X="[object RegExp]",Z="[object Set]",we="[object String]",he="[object Symbol]",de="[object Undefined]",ke="[object WeakMap]",ft="[object WeakSet]",pt="[object ArrayBuffer]",_n="[object DataView]",Cr="[object Float32Array]",ki="[object Float64Array]",_o="[object Int8Array]",Vn="[object Int16Array]",Da="[object Int32Array]",Ri="[object Uint8Array]",zs="[object Uint8ClampedArray]",Ti="[object Uint16Array]",$c="[object Uint32Array]",yg=/\b__p \+= '';/g,wg=/\b(__p \+=) '' \+/g,Kd=/(__e\(.*?\)|\b__t\)) \+\n'';/g,kc=/&(?:amp|lt|gt|quot|#39);/g,Rc=/[&<>"']/g,Tc=RegExp(kc.source),xg=RegExp(Rc.source),Pc=/<%-([\s\S]+?)%>/g,Yd=/<%([\s\S]+?)%>/g,Ac=/<%=([\s\S]+?)%>/g,bg=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,_g=/^\w*$/,Sg=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,H=/[\\^$.*+?()[\]{}|]/g,Ge=RegExp(H.source),st=/^\s+/,Qr=/\s/,an=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Gd=/\{\n\/\* \[wrapped with (.+)\] \*/,oO=/,? & /,iO=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,sO=/[()=,{}\[\]\/\s]/,aO=/\\(\\)?/g,lO=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,db=/\w*$/,cO=/^[-+]0x[0-9a-f]+$/i,uO=/^0b[01]+$/i,dO=/^\[object .+?Constructor\]$/,fO=/^0o[0-7]+$/i,pO=/^(?:0|[1-9]\d*)$/,hO=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Xd=/($^)/,mO=/['\n\r\u2028\u2029\\]/g,Zd="\\ud800-\\udfff",gO="\\u0300-\\u036f",vO="\\ufe20-\\ufe2f",yO="\\u20d0-\\u20ff",fb=gO+vO+yO,pb="\\u2700-\\u27bf",hb="a-z\\xdf-\\xf6\\xf8-\\xff",wO="\\xac\\xb1\\xd7\\xf7",xO="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",bO="\\u2000-\\u206f",_O=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",mb="A-Z\\xc0-\\xd6\\xd8-\\xde",gb="\\ufe0e\\ufe0f",vb=wO+xO+bO+_O,Eg="['’]",SO="["+Zd+"]",yb="["+vb+"]",qd="["+fb+"]",wb="\\d+",EO="["+pb+"]",xb="["+hb+"]",bb="[^"+Zd+vb+wb+pb+hb+mb+"]",Cg="\\ud83c[\\udffb-\\udfff]",CO="(?:"+qd+"|"+Cg+")",_b="[^"+Zd+"]",$g="(?:\\ud83c[\\udde6-\\uddff]){2}",kg="[\\ud800-\\udbff][\\udc00-\\udfff]",Ia="["+mb+"]",Sb="\\u200d",Eb="(?:"+xb+"|"+bb+")",$O="(?:"+Ia+"|"+bb+")",Cb="(?:"+Eg+"(?:d|ll|m|re|s|t|ve))?",$b="(?:"+Eg+"(?:D|LL|M|RE|S|T|VE))?",kb=CO+"?",Rb="["+gb+"]?",kO="(?:"+Sb+"(?:"+[_b,$g,kg].join("|")+")"+Rb+kb+")*",RO="\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",TO="\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])",Tb=Rb+kb+kO,PO="(?:"+[EO,$g,kg].join("|")+")"+Tb,AO="(?:"+[_b+qd+"?",qd,$g,kg,SO].join("|")+")",OO=RegExp(Eg,"g"),MO=RegExp(qd,"g"),Rg=RegExp(Cg+"(?="+Cg+")|"+AO+Tb,"g"),NO=RegExp([Ia+"?"+xb+"+"+Cb+"(?="+[yb,Ia,"$"].join("|")+")",$O+"+"+$b+"(?="+[yb,Ia+Eb,"$"].join("|")+")",Ia+"?"+Eb+"+"+Cb,Ia+"+"+$b,TO,RO,wb,PO].join("|"),"g"),DO=RegExp("["+Sb+Zd+fb+gb+"]"),IO=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,LO=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],FO=-1,kt={};kt[Cr]=kt[ki]=kt[_o]=kt[Vn]=kt[Da]=kt[Ri]=kt[zs]=kt[Ti]=kt[$c]=!0,kt[We]=kt[Me]=kt[pt]=kt[xe]=kt[_n]=kt[$e]=kt[Oe]=kt[je]=kt[ct]=kt[Kt]=kt[gt]=kt[X]=kt[Z]=kt[we]=kt[ke]=!1;var Et={};Et[We]=Et[Me]=Et[pt]=Et[_n]=Et[xe]=Et[$e]=Et[Cr]=Et[ki]=Et[_o]=Et[Vn]=Et[Da]=Et[ct]=Et[Kt]=Et[gt]=Et[X]=Et[Z]=Et[we]=Et[he]=Et[Ri]=Et[zs]=Et[Ti]=Et[$c]=!0,Et[Oe]=Et[je]=Et[ke]=!1;var jO={À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"},zO={"&":"&","<":"<",">":">",'"':""","'":"'"},BO={"&":"&","<":"<",">":">",""":'"',"'":"'"},UO={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},VO=parseFloat,WO=parseInt,Pb=typeof Yc=="object"&&Yc&&Yc.Object===Object&&Yc,HO=typeof self=="object"&&self&&self.Object===Object&&self,fn=Pb||HO||Function("return this")(),Tg=t&&!t.nodeType&&t,Bs=Tg&&!0&&e&&!e.nodeType&&e,Ab=Bs&&Bs.exports===Tg,Pg=Ab&&Pb.process,$r=function(){try{var j=Bs&&Bs.require&&Bs.require("util").types;return j||Pg&&Pg.binding&&Pg.binding("util")}catch{}}(),Ob=$r&&$r.isArrayBuffer,Mb=$r&&$r.isDate,Nb=$r&&$r.isMap,Db=$r&&$r.isRegExp,Ib=$r&&$r.isSet,Lb=$r&&$r.isTypedArray;function or(j,ee,q){switch(q.length){case 0:return j.call(ee);case 1:return j.call(ee,q[0]);case 2:return j.call(ee,q[0],q[1]);case 3:return j.call(ee,q[0],q[1],q[2])}return j.apply(ee,q)}function KO(j,ee,q,_e){for(var Ke=-1,ht=j==null?0:j.length;++Ke-1}function Ag(j,ee,q){for(var _e=-1,Ke=j==null?0:j.length;++_e-1;);return q}function Hb(j,ee){for(var q=j.length;q--&&La(ee,j[q],0)>-1;);return q}function t6(j,ee){for(var q=j.length,_e=0;q--;)j[q]===ee&&++_e;return _e}var n6=Dg(jO),r6=Dg(zO);function o6(j){return"\\"+UO[j]}function i6(j,ee){return j==null?n:j[ee]}function Fa(j){return DO.test(j)}function s6(j){return IO.test(j)}function a6(j){for(var ee,q=[];!(ee=j.next()).done;)q.push(ee.value);return q}function jg(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e,Ke){q[++ee]=[Ke,_e]}),q}function Kb(j,ee){return function(q){return j(ee(q))}}function Oi(j,ee){for(var q=-1,_e=j.length,Ke=0,ht=[];++q<_e;){var en=j[q];(en===ee||en===h)&&(j[q]=h,ht[Ke++]=q)}return ht}function ef(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=_e}),q}function l6(j){var ee=-1,q=Array(j.size);return j.forEach(function(_e){q[++ee]=[_e,_e]}),q}function c6(j,ee,q){for(var _e=q-1,Ke=j.length;++_e-1}function G6(a,c){var p=this.__data__,w=gf(p,a);return w<0?(++this.size,p.push([a,c])):p[w][1]=c,this}Xo.prototype.clear=W6,Xo.prototype.delete=H6,Xo.prototype.get=K6,Xo.prototype.has=Y6,Xo.prototype.set=G6;function Zo(a){var c=-1,p=a==null?0:a.length;for(this.clear();++c=c?a:c)),a}function Pr(a,c,p,w,$,T){var N,D=c&m,B=c&g,ne=c&y;if(p&&(N=$?p(a,w,$,T):p(a)),N!==n)return N;if(!It(a))return a;var re=Ye(a);if(re){if(N=QM(a),!D)return Wn(a,N)}else{var se=En(a),me=se==je||se==Ot;if(Fi(a))return R_(a,D);if(se==gt||se==We||me&&!$){if(N=B||me?{}:Y_(a),!D)return B?BM(a,uM(N,a)):zM(a,o_(N,a))}else{if(!Et[se])return $?a:{};N=JM(a,se,D)}}T||(T=new eo);var Re=T.get(a);if(Re)return Re;T.set(a,N),_S(a)?a.forEach(function(Le){N.add(Pr(Le,c,p,Le,a,T))}):xS(a)&&a.forEach(function(Le,nt){N.set(nt,Pr(Le,c,p,nt,a,T))});var Ie=ne?B?dv:uv:B?Kn:ln,Qe=re?n:Ie(a);return kr(Qe||a,function(Le,nt){Qe&&(nt=Le,Le=a[nt]),Fc(N,nt,Pr(Le,c,p,nt,a,T))}),N}function dM(a){var c=ln(a);return function(p){return i_(p,a,c)}}function i_(a,c,p){var w=p.length;if(a==null)return!w;for(a=_t(a);w--;){var $=p[w],T=c[$],N=a[$];if(N===n&&!($ in a)||!T(N))return!1}return!0}function s_(a,c,p){if(typeof a!="function")throw new Rr(s);return Hc(function(){a.apply(n,p)},c)}function jc(a,c,p,w){var $=-1,T=Qd,N=!0,D=a.length,B=[],ne=c.length;if(!D)return B;p&&(c=Mt(c,ir(p))),w?(T=Ag,N=!1):c.length>=o&&(T=Oc,N=!1,c=new Ws(c));e:for(;++$$?0:$+p),w=w===n||w>$?$:qe(w),w<0&&(w+=$),w=p>w?0:ES(w);p0&&p(D)?c>1?pn(D,c-1,p,w,$):Ai($,D):w||($[$.length]=D)}return $}var Kg=N_(),c_=N_(!0);function So(a,c){return a&&Kg(a,c,ln)}function Yg(a,c){return a&&c_(a,c,ln)}function yf(a,c){return Pi(c,function(p){return ti(a[p])})}function Ks(a,c){c=Ii(c,a);for(var p=0,w=c.length;a!=null&&pc}function hM(a,c){return a!=null&&yt.call(a,c)}function mM(a,c){return a!=null&&c in _t(a)}function gM(a,c,p){return a>=Sn(c,p)&&a=120&&re.length>=120)?new Ws(N&&re):n}re=a[0];var se=-1,me=D[0];e:for(;++se<$&&ne.length-1;)D!==a&&cf.call(D,B,1),cf.call(a,B,1);return a}function x_(a,c){for(var p=a?c.length:0,w=p-1;p--;){var $=c[p];if(p==w||$!==T){var T=$;ei($)?cf.call(a,$,1):rv(a,$)}}return a}function ev(a,c){return a+ff(e_()*(c-a+1))}function TM(a,c,p,w){for(var $=-1,T=tn(df((c-a)/(p||1)),0),N=q(T);T--;)N[w?T:++$]=a,a+=p;return N}function tv(a,c){var p="";if(!a||c<1||c>K)return p;do c%2&&(p+=a),c=ff(c/2),c&&(a+=a);while(c);return p}function et(a,c){return yv(Z_(a,c,Yn),a+"")}function PM(a){return r_(Xa(a))}function AM(a,c){var p=Xa(a);return Tf(p,Hs(c,0,p.length))}function Uc(a,c,p,w){if(!It(a))return a;c=Ii(c,a);for(var $=-1,T=c.length,N=T-1,D=a;D!=null&&++$$?0:$+c),p=p>$?$:p,p<0&&(p+=$),$=c>p?0:p-c>>>0,c>>>=0;for(var T=q($);++w<$;)T[w]=a[w+c];return T}function NM(a,c){var p;return Ni(a,function(w,$,T){return p=c(w,$,T),!p}),!!p}function xf(a,c,p){var w=0,$=a==null?w:a.length;if(typeof c=="number"&&c===c&&$<=Ve){for(;w<$;){var T=w+$>>>1,N=a[T];N!==null&&!ar(N)&&(p?N<=c:N=o){var ne=c?null:HM(a);if(ne)return ef(ne);N=!1,$=Oc,B=new Ws}else B=c?[]:D;e:for(;++w=w?a:Ar(a,c,p)}var k_=_6||function(a){return fn.clearTimeout(a)};function R_(a,c){if(c)return a.slice();var p=a.length,w=Xb?Xb(p):new a.constructor(p);return a.copy(w),w}function av(a){var c=new a.constructor(a.byteLength);return new af(c).set(new af(a)),c}function IM(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.byteLength)}function LM(a){var c=new a.constructor(a.source,db.exec(a));return c.lastIndex=a.lastIndex,c}function FM(a){return Lc?_t(Lc.call(a)):{}}function T_(a,c){var p=c?av(a.buffer):a.buffer;return new a.constructor(p,a.byteOffset,a.length)}function P_(a,c){if(a!==c){var p=a!==n,w=a===null,$=a===a,T=ar(a),N=c!==n,D=c===null,B=c===c,ne=ar(c);if(!D&&!ne&&!T&&a>c||T&&N&&B&&!D&&!ne||w&&N&&B||!p&&B||!$)return 1;if(!w&&!T&&!ne&&a=D)return B;var ne=p[w];return B*(ne=="desc"?-1:1)}}return a.index-c.index}function A_(a,c,p,w){for(var $=-1,T=a.length,N=p.length,D=-1,B=c.length,ne=tn(T-N,0),re=q(B+ne),se=!w;++D1?p[$-1]:n,N=$>2?p[2]:n;for(T=a.length>3&&typeof T=="function"?($--,T):n,N&&Mn(p[0],p[1],N)&&(T=$<3?n:T,$=1),c=_t(c);++w<$;){var D=p[w];D&&a(c,D,w,T)}return c})}function M_(a,c){return function(p,w){if(p==null)return p;if(!Hn(p))return a(p,w);for(var $=p.length,T=c?$:-1,N=_t(p);(c?T--:++T<$)&&w(N[T],T,N)!==!1;);return p}}function N_(a){return function(c,p,w){for(var $=-1,T=_t(c),N=w(c),D=N.length;D--;){var B=N[a?D:++$];if(p(T[B],B,T)===!1)break}return c}}function UM(a,c,p){var w=c&C,$=Vc(a);function T(){var N=this&&this!==fn&&this instanceof T?$:a;return N.apply(w?p:this,arguments)}return T}function D_(a){return function(c){c=vt(c);var p=Fa(c)?Jr(c):n,w=p?p[0]:c.charAt(0),$=p?Li(p,1).join(""):c.slice(1);return w[a]()+$}}function Ka(a){return function(c){return Og(MS(OS(c).replace(OO,"")),a,"")}}function Vc(a){return function(){var c=arguments;switch(c.length){case 0:return new a;case 1:return new a(c[0]);case 2:return new a(c[0],c[1]);case 3:return new a(c[0],c[1],c[2]);case 4:return new a(c[0],c[1],c[2],c[3]);case 5:return new a(c[0],c[1],c[2],c[3],c[4]);case 6:return new a(c[0],c[1],c[2],c[3],c[4],c[5]);case 7:return new a(c[0],c[1],c[2],c[3],c[4],c[5],c[6])}var p=Wa(a.prototype),w=a.apply(p,c);return It(w)?w:p}}function VM(a,c,p){var w=Vc(a);function $(){for(var T=arguments.length,N=q(T),D=T,B=Ya($);D--;)N[D]=arguments[D];var ne=T<3&&N[0]!==B&&N[T-1]!==B?[]:Oi(N,B);if(T-=ne.length,T-1?$[T?c[N]:N]:n}}function L_(a){return Jo(function(c){var p=c.length,w=p,$=Tr.prototype.thru;for(a&&c.reverse();w--;){var T=c[w];if(typeof T!="function")throw new Rr(s);if($&&!N&&kf(T)=="wrapper")var N=new Tr([],!0)}for(w=N?w:p;++w1&&at.reverse(),re&&BD))return!1;var ne=T.get(a),re=T.get(c);if(ne&&re)return ne==c&&re==a;var se=-1,me=!0,Re=p&_?new Ws:n;for(T.set(a,c),T.set(c,a);++se1?"& ":"")+c[w],c=c.join(p>2?", ":" "),a.replace(an,`{ +/* [wrapped with `+c+`] */ +`)}function tN(a){return Ye(a)||Xs(a)||!!(Qb&&a&&a[Qb])}function ei(a,c){var p=typeof a;return c=c??K,!!c&&(p=="number"||p!="symbol"&&pO.test(a))&&a>-1&&a%1==0&&a0){if(++c>=G)return arguments[0]}else c=0;return a.apply(n,arguments)}}function Tf(a,c){var p=-1,w=a.length,$=w-1;for(c=c===n?w:c;++p1?a[c-1]:n;return p=typeof p=="function"?(a.pop(),p):n,lS(a,p)});function cS(a){var c=R(a);return c.__chain__=!0,c}function f7(a,c){return c(a),a}function Pf(a,c){return c(a)}var p7=Jo(function(a){var c=a.length,p=c?a[0]:0,w=this.__wrapped__,$=function(T){return Hg(T,a)};return c>1||this.__actions__.length||!(w instanceof ot)||!ei(p)?this.thru($):(w=w.slice(p,+p+(c?1:0)),w.__actions__.push({func:Pf,args:[$],thisArg:n}),new Tr(w,this.__chain__).thru(function(T){return c&&!T.length&&T.push(n),T}))});function h7(){return cS(this)}function m7(){return new Tr(this.value(),this.__chain__)}function g7(){this.__values__===n&&(this.__values__=SS(this.value()));var a=this.__index__>=this.__values__.length,c=a?n:this.__values__[this.__index__++];return{done:a,value:c}}function v7(){return this}function y7(a){for(var c,p=this;p instanceof mf;){var w=nS(p);w.__index__=0,w.__values__=n,c?$.__wrapped__=w:c=w;var $=w;p=p.__wrapped__}return $.__wrapped__=a,c}function w7(){var a=this.__wrapped__;if(a instanceof ot){var c=a;return this.__actions__.length&&(c=new ot(this)),c=c.reverse(),c.__actions__.push({func:Pf,args:[wv],thisArg:n}),new Tr(c,this.__chain__)}return this.thru(wv)}function x7(){return C_(this.__wrapped__,this.__actions__)}var b7=_f(function(a,c,p){yt.call(a,p)?++a[p]:qo(a,p,1)});function _7(a,c,p){var w=Ye(a)?Fb:fM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}function S7(a,c){var p=Ye(a)?Pi:l_;return p(a,De(c,3))}var E7=I_(rS),C7=I_(oS);function $7(a,c){return pn(Af(a,c),1)}function k7(a,c){return pn(Af(a,c),ie)}function R7(a,c,p){return p=p===n?1:qe(p),pn(Af(a,c),p)}function uS(a,c){var p=Ye(a)?kr:Ni;return p(a,De(c,3))}function dS(a,c){var p=Ye(a)?YO:a_;return p(a,De(c,3))}var T7=_f(function(a,c,p){yt.call(a,p)?a[p].push(c):qo(a,p,[c])});function P7(a,c,p,w){a=Hn(a)?a:Xa(a),p=p&&!w?qe(p):0;var $=a.length;return p<0&&(p=tn($+p,0)),If(a)?p<=$&&a.indexOf(c,p)>-1:!!$&&La(a,c,p)>-1}var A7=et(function(a,c,p){var w=-1,$=typeof c=="function",T=Hn(a)?q(a.length):[];return Ni(a,function(N){T[++w]=$?or(c,N,p):zc(N,c,p)}),T}),O7=_f(function(a,c,p){qo(a,p,c)});function Af(a,c){var p=Ye(a)?Mt:h_;return p(a,De(c,3))}function M7(a,c,p,w){return a==null?[]:(Ye(c)||(c=c==null?[]:[c]),p=w?n:p,Ye(p)||(p=p==null?[]:[p]),y_(a,c,p))}var N7=_f(function(a,c,p){a[p?0:1].push(c)},function(){return[[],[]]});function D7(a,c,p){var w=Ye(a)?Og:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,Ni)}function I7(a,c,p){var w=Ye(a)?GO:Ub,$=arguments.length<3;return w(a,De(c,4),p,$,a_)}function L7(a,c){var p=Ye(a)?Pi:l_;return p(a,Nf(De(c,3)))}function F7(a){var c=Ye(a)?r_:PM;return c(a)}function j7(a,c,p){(p?Mn(a,c,p):c===n)?c=1:c=qe(c);var w=Ye(a)?aM:AM;return w(a,c)}function z7(a){var c=Ye(a)?lM:MM;return c(a)}function B7(a){if(a==null)return 0;if(Hn(a))return If(a)?ja(a):a.length;var c=En(a);return c==ct||c==Z?a.size:qg(a).length}function U7(a,c,p){var w=Ye(a)?Mg:NM;return p&&Mn(a,c,p)&&(c=n),w(a,De(c,3))}var V7=et(function(a,c){if(a==null)return[];var p=c.length;return p>1&&Mn(a,c[0],c[1])?c=[]:p>2&&Mn(c[0],c[1],c[2])&&(c=[c[0]]),y_(a,pn(c,1),[])}),Of=S6||function(){return fn.Date.now()};function W7(a,c){if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){if(--a<1)return c.apply(this,arguments)}}function fS(a,c,p){return c=p?n:c,c=a&&c==null?a.length:c,Qo(a,A,n,n,n,n,c)}function pS(a,c){var p;if(typeof c!="function")throw new Rr(s);return a=qe(a),function(){return--a>0&&(p=c.apply(this,arguments)),a<=1&&(c=n),p}}var bv=et(function(a,c,p){var w=C;if(p.length){var $=Oi(p,Ya(bv));w|=P}return Qo(a,w,c,p,$)}),hS=et(function(a,c,p){var w=C|S;if(p.length){var $=Oi(p,Ya(hS));w|=P}return Qo(c,w,a,p,$)});function mS(a,c,p){c=p?n:c;var w=Qo(a,E,n,n,n,n,n,c);return w.placeholder=mS.placeholder,w}function gS(a,c,p){c=p?n:c;var w=Qo(a,k,n,n,n,n,n,c);return w.placeholder=gS.placeholder,w}function vS(a,c,p){var w,$,T,N,D,B,ne=0,re=!1,se=!1,me=!0;if(typeof a!="function")throw new Rr(s);c=Mr(c)||0,It(p)&&(re=!!p.leading,se="maxWait"in p,T=se?tn(Mr(p.maxWait)||0,c):T,me="trailing"in p?!!p.trailing:me);function Re(Gt){var no=w,ri=$;return w=$=n,ne=Gt,N=a.apply(ri,no),N}function Ie(Gt){return ne=Gt,D=Hc(nt,c),re?Re(Gt):N}function Qe(Gt){var no=Gt-B,ri=Gt-ne,IS=c-no;return se?Sn(IS,T-ri):IS}function Le(Gt){var no=Gt-B,ri=Gt-ne;return B===n||no>=c||no<0||se&&ri>=T}function nt(){var Gt=Of();if(Le(Gt))return at(Gt);D=Hc(nt,Qe(Gt))}function at(Gt){return D=n,me&&w?Re(Gt):(w=$=n,N)}function lr(){D!==n&&k_(D),ne=0,w=B=$=D=n}function Nn(){return D===n?N:at(Of())}function cr(){var Gt=Of(),no=Le(Gt);if(w=arguments,$=this,B=Gt,no){if(D===n)return Ie(B);if(se)return k_(D),D=Hc(nt,c),Re(B)}return D===n&&(D=Hc(nt,c)),N}return cr.cancel=lr,cr.flush=Nn,cr}var H7=et(function(a,c){return s_(a,1,c)}),K7=et(function(a,c,p){return s_(a,Mr(c)||0,p)});function Y7(a){return Qo(a,F)}function Mf(a,c){if(typeof a!="function"||c!=null&&typeof c!="function")throw new Rr(s);var p=function(){var w=arguments,$=c?c.apply(this,w):w[0],T=p.cache;if(T.has($))return T.get($);var N=a.apply(this,w);return p.cache=T.set($,N)||T,N};return p.cache=new(Mf.Cache||Zo),p}Mf.Cache=Zo;function Nf(a){if(typeof a!="function")throw new Rr(s);return function(){var c=arguments;switch(c.length){case 0:return!a.call(this);case 1:return!a.call(this,c[0]);case 2:return!a.call(this,c[0],c[1]);case 3:return!a.call(this,c[0],c[1],c[2])}return!a.apply(this,c)}}function G7(a){return pS(2,a)}var X7=DM(function(a,c){c=c.length==1&&Ye(c[0])?Mt(c[0],ir(De())):Mt(pn(c,1),ir(De()));var p=c.length;return et(function(w){for(var $=-1,T=Sn(w.length,p);++$=c}),Xs=d_(function(){return arguments}())?d_:function(a){return Bt(a)&&yt.call(a,"callee")&&!qb.call(a,"callee")},Ye=q.isArray,u4=Ob?ir(Ob):yM;function Hn(a){return a!=null&&Df(a.length)&&!ti(a)}function Yt(a){return Bt(a)&&Hn(a)}function d4(a){return a===!0||a===!1||Bt(a)&&On(a)==xe}var Fi=C6||Mv,f4=Mb?ir(Mb):wM;function p4(a){return Bt(a)&&a.nodeType===1&&!Kc(a)}function h4(a){if(a==null)return!0;if(Hn(a)&&(Ye(a)||typeof a=="string"||typeof a.splice=="function"||Fi(a)||Ga(a)||Xs(a)))return!a.length;var c=En(a);if(c==ct||c==Z)return!a.size;if(Wc(a))return!qg(a).length;for(var p in a)if(yt.call(a,p))return!1;return!0}function m4(a,c){return Bc(a,c)}function g4(a,c,p){p=typeof p=="function"?p:n;var w=p?p(a,c):n;return w===n?Bc(a,c,n,p):!!w}function Sv(a){if(!Bt(a))return!1;var c=On(a);return c==Oe||c==Ae||typeof a.message=="string"&&typeof a.name=="string"&&!Kc(a)}function v4(a){return typeof a=="number"&&Jb(a)}function ti(a){if(!It(a))return!1;var c=On(a);return c==je||c==Ot||c==fe||c==I}function wS(a){return typeof a=="number"&&a==qe(a)}function Df(a){return typeof a=="number"&&a>-1&&a%1==0&&a<=K}function It(a){var c=typeof a;return a!=null&&(c=="object"||c=="function")}function Bt(a){return a!=null&&typeof a=="object"}var xS=Nb?ir(Nb):bM;function y4(a,c){return a===c||Zg(a,c,pv(c))}function w4(a,c,p){return p=typeof p=="function"?p:n,Zg(a,c,pv(c),p)}function x4(a){return bS(a)&&a!=+a}function b4(a){if(oN(a))throw new Ke(i);return f_(a)}function _4(a){return a===null}function S4(a){return a==null}function bS(a){return typeof a=="number"||Bt(a)&&On(a)==Kt}function Kc(a){if(!Bt(a)||On(a)!=gt)return!1;var c=lf(a);if(c===null)return!0;var p=yt.call(c,"constructor")&&c.constructor;return typeof p=="function"&&p instanceof p&&rf.call(p)==w6}var Ev=Db?ir(Db):_M;function E4(a){return wS(a)&&a>=-K&&a<=K}var _S=Ib?ir(Ib):SM;function If(a){return typeof a=="string"||!Ye(a)&&Bt(a)&&On(a)==we}function ar(a){return typeof a=="symbol"||Bt(a)&&On(a)==he}var Ga=Lb?ir(Lb):EM;function C4(a){return a===n}function $4(a){return Bt(a)&&En(a)==ke}function k4(a){return Bt(a)&&On(a)==ft}var R4=$f(Qg),T4=$f(function(a,c){return a<=c});function SS(a){if(!a)return[];if(Hn(a))return If(a)?Jr(a):Wn(a);if(Mc&&a[Mc])return a6(a[Mc]());var c=En(a),p=c==ct?jg:c==Z?ef:Xa;return p(a)}function ni(a){if(!a)return a===0?a:0;if(a=Mr(a),a===ie||a===-ie){var c=a<0?-1:1;return c*Q}return a===a?a:0}function qe(a){var c=ni(a),p=c%1;return c===c?p?c-p:c:0}function ES(a){return a?Hs(qe(a),0,le):0}function Mr(a){if(typeof a=="number")return a;if(ar(a))return W;if(It(a)){var c=typeof a.valueOf=="function"?a.valueOf():a;a=It(c)?c+"":c}if(typeof a!="string")return a===0?a:+a;a=Vb(a);var p=uO.test(a);return p||fO.test(a)?WO(a.slice(2),p?2:8):cO.test(a)?W:+a}function CS(a){return Eo(a,Kn(a))}function P4(a){return a?Hs(qe(a),-K,K):a===0?a:0}function vt(a){return a==null?"":sr(a)}var A4=Ha(function(a,c){if(Wc(c)||Hn(c)){Eo(c,ln(c),a);return}for(var p in c)yt.call(c,p)&&Fc(a,p,c[p])}),$S=Ha(function(a,c){Eo(c,Kn(c),a)}),Lf=Ha(function(a,c,p,w){Eo(c,Kn(c),a,w)}),O4=Ha(function(a,c,p,w){Eo(c,ln(c),a,w)}),M4=Jo(Hg);function N4(a,c){var p=Wa(a);return c==null?p:o_(p,c)}var D4=et(function(a,c){a=_t(a);var p=-1,w=c.length,$=w>2?c[2]:n;for($&&Mn(c[0],c[1],$)&&(w=1);++p1),T}),Eo(a,dv(a),p),w&&(p=Pr(p,m|g|y,KM));for(var $=c.length;$--;)rv(p,c[$]);return p});function J4(a,c){return RS(a,Nf(De(c)))}var e8=Jo(function(a,c){return a==null?{}:kM(a,c)});function RS(a,c){if(a==null)return{};var p=Mt(dv(a),function(w){return[w]});return c=De(c),w_(a,p,function(w,$){return c(w,$[0])})}function t8(a,c,p){c=Ii(c,a);var w=-1,$=c.length;for($||($=1,a=n);++w<$;){var T=a==null?n:a[Co(c[w])];T===n&&(w=$,T=p),a=ti(T)?T.call(a):T}return a}function n8(a,c,p){return a==null?a:Uc(a,c,p)}function r8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:Uc(a,c,p,w)}var TS=B_(ln),PS=B_(Kn);function o8(a,c,p){var w=Ye(a),$=w||Fi(a)||Ga(a);if(c=De(c,4),p==null){var T=a&&a.constructor;$?p=w?new T:[]:It(a)?p=ti(T)?Wa(lf(a)):{}:p={}}return($?kr:So)(a,function(N,D,B){return c(p,N,D,B)}),p}function i8(a,c){return a==null?!0:rv(a,c)}function s8(a,c,p){return a==null?a:E_(a,c,sv(p))}function a8(a,c,p,w){return w=typeof w=="function"?w:n,a==null?a:E_(a,c,sv(p),w)}function Xa(a){return a==null?[]:Fg(a,ln(a))}function l8(a){return a==null?[]:Fg(a,Kn(a))}function c8(a,c,p){return p===n&&(p=c,c=n),p!==n&&(p=Mr(p),p=p===p?p:0),c!==n&&(c=Mr(c),c=c===c?c:0),Hs(Mr(a),c,p)}function u8(a,c,p){return c=ni(c),p===n?(p=c,c=0):p=ni(p),a=Mr(a),gM(a,c,p)}function d8(a,c,p){if(p&&typeof p!="boolean"&&Mn(a,c,p)&&(c=p=n),p===n&&(typeof c=="boolean"?(p=c,c=n):typeof a=="boolean"&&(p=a,a=n)),a===n&&c===n?(a=0,c=1):(a=ni(a),c===n?(c=a,a=0):c=ni(c)),a>c){var w=a;a=c,c=w}if(p||a%1||c%1){var $=e_();return Sn(a+$*(c-a+VO("1e-"+(($+"").length-1))),c)}return ev(a,c)}var f8=Ka(function(a,c,p){return c=c.toLowerCase(),a+(p?AS(c):c)});function AS(a){return kv(vt(a).toLowerCase())}function OS(a){return a=vt(a),a&&a.replace(hO,n6).replace(MO,"")}function p8(a,c,p){a=vt(a),c=sr(c);var w=a.length;p=p===n?w:Hs(qe(p),0,w);var $=p;return p-=c.length,p>=0&&a.slice(p,$)==c}function h8(a){return a=vt(a),a&&xg.test(a)?a.replace(Rc,r6):a}function m8(a){return a=vt(a),a&&Ge.test(a)?a.replace(H,"\\$&"):a}var g8=Ka(function(a,c,p){return a+(p?"-":"")+c.toLowerCase()}),v8=Ka(function(a,c,p){return a+(p?" ":"")+c.toLowerCase()}),y8=D_("toLowerCase");function w8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;if(!c||w>=c)return a;var $=(c-w)/2;return Cf(ff($),p)+a+Cf(df($),p)}function x8(a,c,p){a=vt(a),c=qe(c);var w=c?ja(a):0;return c&&w>>0,p?(a=vt(a),a&&(typeof c=="string"||c!=null&&!Ev(c))&&(c=sr(c),!c&&Fa(a))?Li(Jr(a),0,p):a.split(c,p)):[]}var k8=Ka(function(a,c,p){return a+(p?" ":"")+kv(c)});function R8(a,c,p){return a=vt(a),p=p==null?0:Hs(qe(p),0,a.length),c=sr(c),a.slice(p,p+c.length)==c}function T8(a,c,p){var w=R.templateSettings;p&&Mn(a,c,p)&&(c=n),a=vt(a),c=Lf({},c,w,U_);var $=Lf({},c.imports,w.imports,U_),T=ln($),N=Fg($,T),D,B,ne=0,re=c.interpolate||Xd,se="__p += '",me=zg((c.escape||Xd).source+"|"+re.source+"|"+(re===Ac?lO:Xd).source+"|"+(c.evaluate||Xd).source+"|$","g"),Re="//# sourceURL="+(yt.call(c,"sourceURL")?(c.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++FO+"]")+` +`;a.replace(me,function(Le,nt,at,lr,Nn,cr){return at||(at=lr),se+=a.slice(ne,cr).replace(mO,o6),nt&&(D=!0,se+=`' + +__e(`+nt+`) + +'`),Nn&&(B=!0,se+=`'; +`+Nn+`; +__p += '`),at&&(se+=`' + +((__t = (`+at+`)) == null ? '' : __t) + +'`),ne=cr+Le.length,Le}),se+=`'; +`;var Ie=yt.call(c,"variable")&&c.variable;if(!Ie)se=`with (obj) { +`+se+` +} +`;else if(sO.test(Ie))throw new Ke(l);se=(B?se.replace(yg,""):se).replace(wg,"$1").replace(Kd,"$1;"),se="function("+(Ie||"obj")+`) { +`+(Ie?"":`obj || (obj = {}); +`)+"var __t, __p = ''"+(D?", __e = _.escape":"")+(B?`, __j = Array.prototype.join; +function print() { __p += __j.call(arguments, '') } +`:`; +`)+se+`return __p +}`;var Qe=NS(function(){return ht(T,Re+"return "+se).apply(n,N)});if(Qe.source=se,Sv(Qe))throw Qe;return Qe}function P8(a){return vt(a).toLowerCase()}function A8(a){return vt(a).toUpperCase()}function O8(a,c,p){if(a=vt(a),a&&(p||c===n))return Vb(a);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Jr(c),T=Wb(w,$),N=Hb(w,$)+1;return Li(w,T,N).join("")}function M8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.slice(0,Yb(a)+1);if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Hb(w,Jr(c))+1;return Li(w,0,$).join("")}function N8(a,c,p){if(a=vt(a),a&&(p||c===n))return a.replace(st,"");if(!a||!(c=sr(c)))return a;var w=Jr(a),$=Wb(w,Jr(c));return Li(w,$).join("")}function D8(a,c){var p=V,w=J;if(It(c)){var $="separator"in c?c.separator:$;p="length"in c?qe(c.length):p,w="omission"in c?sr(c.omission):w}a=vt(a);var T=a.length;if(Fa(a)){var N=Jr(a);T=N.length}if(p>=T)return a;var D=p-ja(w);if(D<1)return w;var B=N?Li(N,0,D).join(""):a.slice(0,D);if($===n)return B+w;if(N&&(D+=B.length-D),Ev($)){if(a.slice(D).search($)){var ne,re=B;for($.global||($=zg($.source,vt(db.exec($))+"g")),$.lastIndex=0;ne=$.exec(re);)var se=ne.index;B=B.slice(0,se===n?D:se)}}else if(a.indexOf(sr($),D)!=D){var me=B.lastIndexOf($);me>-1&&(B=B.slice(0,me))}return B+w}function I8(a){return a=vt(a),a&&Tc.test(a)?a.replace(kc,d6):a}var L8=Ka(function(a,c,p){return a+(p?" ":"")+c.toUpperCase()}),kv=D_("toUpperCase");function MS(a,c,p){return a=vt(a),c=p?n:c,c===n?s6(a)?h6(a):qO(a):a.match(c)||[]}var NS=et(function(a,c){try{return or(a,n,c)}catch(p){return Sv(p)?p:new Ke(p)}}),F8=Jo(function(a,c){return kr(c,function(p){p=Co(p),qo(a,p,bv(a[p],a))}),a});function j8(a){var c=a==null?0:a.length,p=De();return a=c?Mt(a,function(w){if(typeof w[1]!="function")throw new Rr(s);return[p(w[0]),w[1]]}):[],et(function(w){for(var $=-1;++$K)return[];var p=le,w=Sn(a,le);c=De(c),a-=le;for(var $=Lg(w,c);++p0||c<0)?new ot(p):(a<0?p=p.takeRight(-a):a&&(p=p.drop(a)),c!==n&&(c=qe(c),p=c<0?p.dropRight(-c):p.take(c-a)),p)},ot.prototype.takeRightWhile=function(a){return this.reverse().takeWhile(a).reverse()},ot.prototype.toArray=function(){return this.take(le)},So(ot.prototype,function(a,c){var p=/^(?:filter|find|map|reject)|While$/.test(c),w=/^(?:head|last)$/.test(c),$=R[w?"take"+(c=="last"?"Right":""):c],T=w||/^find/.test(c);$&&(R.prototype[c]=function(){var N=this.__wrapped__,D=w?[1]:arguments,B=N instanceof ot,ne=D[0],re=B||Ye(N),se=function(nt){var at=$.apply(R,Ai([nt],D));return w&&me?at[0]:at};re&&p&&typeof ne=="function"&&ne.length!=1&&(B=re=!1);var me=this.__chain__,Re=!!this.__actions__.length,Ie=T&&!me,Qe=B&&!Re;if(!T&&re){N=Qe?N:new ot(this);var Le=a.apply(N,D);return Le.__actions__.push({func:Pf,args:[se],thisArg:n}),new Tr(Le,me)}return Ie&&Qe?a.apply(this,D):(Le=this.thru(se),Ie?w?Le.value()[0]:Le.value():Le)})}),kr(["pop","push","shift","sort","splice","unshift"],function(a){var c=tf[a],p=/^(?:push|sort|unshift)$/.test(a)?"tap":"thru",w=/^(?:pop|shift)$/.test(a);R.prototype[a]=function(){var $=arguments;if(w&&!this.__chain__){var T=this.value();return c.apply(Ye(T)?T:[],$)}return this[p](function(N){return c.apply(Ye(N)?N:[],$)})}}),So(ot.prototype,function(a,c){var p=R[c];if(p){var w=p.name+"";yt.call(Va,w)||(Va[w]=[]),Va[w].push({name:c,func:p})}}),Va[Sf(n,S).name]=[{name:"wrapper",func:n}],ot.prototype.clone=I6,ot.prototype.reverse=L6,ot.prototype.value=F6,R.prototype.at=p7,R.prototype.chain=h7,R.prototype.commit=m7,R.prototype.next=g7,R.prototype.plant=y7,R.prototype.reverse=w7,R.prototype.toJSON=R.prototype.valueOf=R.prototype.value=x7,R.prototype.first=R.prototype.head,Mc&&(R.prototype[Mc]=v7),R},za=m6();Bs?((Bs.exports=za)._=za,Tg._=za):fn._=za}).call(Yc)})(Lh,Lh.exports);var yH=Lh.exports;const wH=lm(yH);function Vr({width:e,height:t}){return e/t}function Fh(e,t=0){const n=10**t;return Math.round((e+Number.EPSILON)*n)/n}function xH(e){return(t,n)=>e(n)-e(t)}class bH{constructor(t){this.comparator=t,this.heap=[],this.n=0}greater(t,n){return this.comparator(this.heap[t],this.heap[n])<0}swap(t,n){const r=this.heap[t];this.heap[t]=this.heap[n],this.heap[n]=r}swim(t){let n=t,r=Math.floor(n/2);for(;n>1&&this.greater(r,n);)this.swap(r,n),n=r,r=Math.floor(n/2)}sink(t){let n=t,r=n*2;for(;r<=this.n&&(rl.weight));for(s.push({id:t,weight:0});s.size()>0;){const{id:l,weight:u}=s.pop();if(!o.has(l)){const d=e(l);o.add(l),d.forEach((h,m)=>{const g=u+h,y=r.get(m),x=i.get(m);(x===void 0||x>g&&(x/g>1.005||y!==void 0&&yMath.min(Vr(i),o),Number.MAX_VALUE);return Fh(n/t/r)+2}function MP(e,t,n,r){const o=t-(e.length-1)*n-2*r*e.length,i=e.reduce((s,l)=>s+Vr(l),0);return o/i}function $H(e,t,n,r,o,i,s){const l=e.slice(t,n),u=MP(l,r,i,s);return u>0?(u-o)**2*l.length:void 0}function kH({photos:e,layoutOptions:t,targetRowHeight:n,limitNodeSearch:r,rowConstraints:o}){return i=>{var s,l;const{containerWidth:u,spacing:d,padding:h}=t,m=new Map;m.set(i,0);const g=(s=o==null?void 0:o.minPhotos)!=null?s:1,y=Math.min(r,(l=o==null?void 0:o.maxPhotos)!=null?l:1/0);for(let x=i+g;xy);x+=1){const _=$H(e,i,x,u,n,d,h);if(_===void 0)break;m.set(x,_)}return m}}function RH({photos:e,layoutOptions:t}){const{spacing:n,padding:r,containerWidth:o,targetRowHeight:i,rowConstraints:s}=t,l=CH({photos:e,containerWidth:o,targetRowHeight:i}),u=kH({photos:e,layoutOptions:t,targetRowHeight:i,limitNodeSearch:l,rowConstraints:s}),d=EH(u,0,e.length);if(d===void 0)return;const h=[];for(let m=1;m({photo:x,index:_})).slice(d[m-1],d[m]),y=MP(g.map(({photo:x})=>x),o,n,r);h.push(g.map(({photo:x,index:_},C)=>({photo:x,layout:{height:y,width:y*Vr(x),index:_,photoIndex:C,photosCount:g.length}})))}return h}function qm(...e){return[...e].filter(t=>!!t).join(" ")}function NP(e,{width:t,photosCount:n},{spacing:r,padding:o,containerWidth:i}){const s=r*(n-1)+2*o*n;return`calc((${e} - ${s}px) / ${Fh((i-s)/t,5)})`}function TH(e,t){return t.layout!=="rows"?`calc(100% - ${2*t.padding}px)`:NP("100%",e,t)}function i2(e,t,n){var r,o;return NP((o=(r=e.match(/calc\((.*)\)/))==null?void 0:r[1])!=null?o:e,t,n)}function PH(e,t,n){let r,o;const i=e.srcSet||e.images;return i&&i.length>0&&(r=i.concat(i.find(({width:s})=>s===e.width)?[]:[{src:e.src,width:e.width,height:e.height}]).sort((s,l)=>s.width-l.width).map(s=>`${s.src} ${s.width}w`).join(", ")),n.sizes?o=(n.sizes.sizes||[]).map(({viewport:s,size:l})=>`${s} ${i2(l,t,n)}`).concat(i2(n.sizes.size,t,n)).join(", "):r&&(o=`${Math.ceil(t.width/n.containerWidth*100)}vw`),{srcSet:r,sizes:o}}function Ox(e){var t,n;const{photo:r,layout:o,layoutOptions:i,imageProps:{style:s,className:l,...u}={},renderPhoto:d}=e,{onClick:h}=i,m={display:"block",boxSizing:"content-box",width:TH(o,i),height:"auto",aspectRatio:`${r.width} / ${r.height}`,...i.padding?{padding:`${i.padding}px`}:null,...(i.layout==="columns"||i.layout==="masonry")&&o.photoIndex{h({event:C,photo:r,index:o.index})}:void 0,y={src:r.src,alt:(t=r.alt)!=null?t:"",title:r.title,onClick:g,style:m,className:qm("react-photo-album--photo",l),loading:"lazy",decoding:"async",...PH(r,o,i),...u},x=C=>{const{src:S,alt:b,srcSet:E,sizes:k,style:P,...M}=y;return f.createElement("img",{alt:b,...E?{srcSet:E,sizes:k}:null,src:S,style:C!=null&&C.wrapped?{display:"block",width:"100%",height:"100%"}:P,...M})},_=(({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M})=>({display:C,boxSizing:S,width:b,aspectRatio:E,padding:k,marginBottom:P,cursor:M}))(m);return f.createElement(f.Fragment,null,(n=d==null?void 0:d({photo:r,layout:o,layoutOptions:i,imageProps:y,renderDefaultPhoto:x,wrapperStyle:_}))!=null?n:x())}function AH({rowContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function OH(e){const{layoutOptions:t,rowIndex:n,rowsCount:r,renderRowContainer:o,rowContainerProps:{style:i,className:s,...l}={},children:u}=e,d={className:qm("react-photo-album--row",s),style:{display:"flex",flexDirection:"row",flexWrap:"nowrap",alignItems:"flex-start",justifyContent:"space-between",...nf.createElement(OH,{key:`row-${d}`,layoutOptions:n,rowIndex:d,rowsCount:l.length,renderRowContainer:o,rowContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function NH(e,t,n,r){const o=new Map,i=new Set;i.add(n);for(let s=0;s{const d=s>0?o.get(u)[s].weight:0;e(u).forEach(({neighbor:h,weight:m})=>{let g=o.get(h);g||(g=[],o.set(h,g));const y=d+m,x=g[s+1];(!x||x.weight>y&&(x.weight/y>1.0001||u0;i-=1)o=e.get(o)[i].node,r.push(o);return r.reverse()}function IH(e,t,n,r){return DH(NH(e,t,n,r),t,r)}function LH({photos:e,spacing:t,padding:n,targetColumnWidth:r,targetColumnHeight:o}){return i=>{const s=[],l=o*1.5;let u=r/Vr(e[i])+2*n;for(let d=i+1;dl||d===e.length));d+=1)u+=r/Vr(e[d])+t+2*n;return s}}function s2({path:e,photos:t,containerWidth:n,columnsGaps:r,columnsRatios:o,spacing:i,padding:s}){const l=[],u=o.reduce((d,h)=>d+h,0);for(let d=0;d({photo:y,index:x})).slice(e[d],e[d+1]),m=o.reduce((y,x,_)=>y+(r[d]-r[_])*x,0),g=(n-(e.length-2)*i-2*(e.length-1)*s-m)*o[d]/u;l.push(h.map(({photo:y,index:x},_)=>({photo:y,layout:{width:g,height:g/Vr(y),index:x,photoIndex:_,photosCount:h.length}})))}return l}function FH({photos:e,layoutOptions:t,targetColumnWidth:n}){const{columns:r,spacing:o,padding:i,containerWidth:s}=t,l=[],u=[];if(e.length<=r){const y=e.length>0?e.reduce((_,C)=>_+Vr(C),0)/e.length:1;for(let _=0;_Math.min(C,e.length)),photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:x}}const d=(e.reduce((y,x)=>y+n/Vr(x),0)+o*(e.length-r)+2*i*e.length)/r,h=LH({photos:e,targetColumnWidth:n,targetColumnHeight:d,spacing:o,padding:i}),m=IH(h,r,0,e.length);for(let y=0;y_+1/Vr(C),0)}const g=s2({path:m,photos:e,columnsRatios:u,columnsGaps:l,containerWidth:s,spacing:o,padding:i});return{columnsGaps:l,columnsRatios:u,columnsModel:g}}function DP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r,{columnsGaps:u,columnsRatios:d,columnsModel:h}=FH({photos:t,layoutOptions:n,targetColumnWidth:l});return h.findIndex(m=>m.findIndex(({layout:{width:g,height:y}})=>g<0||y<0)>=0)>=0?r>1?DP({photos:t,layoutOptions:{...n,columns:r-1}}):void 0:{columnsModel:h,columnsGaps:u,columnsRatios:d}}function jH({photos:e,layoutOptions:t}){return DP({photos:e,layoutOptions:t})}function zH({columnContainerProps:e,children:t}){return f.createElement("div",{...e},t)}function BH(e){const{layoutOptions:t,columnIndex:n,columnsCount:r,columnsGaps:o,columnsRatios:i}=e,{layout:s,spacing:l,padding:u}=t;if(s==="masonry"||!o||!i)return`calc((100% - ${l*(r-1)}px) / ${r})`;const d=i.reduce((m,g)=>m+g,0),h=i.reduce((m,g,y)=>m+(o[n]-o[y])*g,0);return`calc((100% - ${Fh((r-1)*l+2*r*u+h,3)}px) * ${Fh(i[n]/d,5)} + ${2*u}px)`}function IP(e){const{layoutOptions:t,renderColumnContainer:n,children:r,columnContainerProps:{style:o,className:i,...s}={},...l}=e,u={className:qm("react-photo-album--column",i),style:{display:"flex",flexDirection:"column",flexWrap:"nowrap",alignItems:"flex-start",width:BH(e),justifyContent:t.layout==="columns"?"space-between":"flex-start",...o},...s};return f.createElement(f.Fragment,null,(n??zH)({layoutOptions:t,columnContainerProps:u,children:r,...l}))}function UH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=jH({photos:t,layoutOptions:n});if(!l)return null;const{columnsModel:u,columnsRatios:d,columnsGaps:h}=l;return f.createElement(f.Fragment,null,u.map((m,g)=>f.createElement(IP,{key:`column-${g}`,layoutOptions:n,columnIndex:g,columnsCount:u.length,columnsGaps:h,columnsRatios:d,renderColumnContainer:o,columnContainerProps:s},m.map(({photo:y,layout:x})=>f.createElement(Ox,{key:y.key||y.src,photo:y,layout:x,layoutOptions:n,renderPhoto:r,imageProps:i})))))}function LP(e){const{photos:t,layoutOptions:n}=e,{columns:r,spacing:o,padding:i,containerWidth:s}=n,l=(s-o*(r-1)-2*i*r)/r;if(l<=0)return r>1?LP({...e,layoutOptions:{...n,columns:r-1}}):void 0;const u=[];for(let h=0;h{const y=u.reduce((x,_,C)=>_[])).map(h=>h.map(({photo:m,index:g},y)=>({photo:m,layout:{width:l,height:l/Vr(m),index:g,photoIndex:y,photosCount:h.length}})))}function VH(e){const{photos:t,layoutOptions:n,renderPhoto:r,renderColumnContainer:o,componentsProps:{imageProps:i,columnContainerProps:s}}=e,l=LP({photos:t,layoutOptions:n});return l?f.createElement(f.Fragment,null,l.map((u,d)=>f.createElement(IP,{key:`masonry-column-${d}`,layoutOptions:n,columnsCount:l.length,columnIndex:d,renderColumnContainer:o,columnContainerProps:s},u.map(({photo:h,layout:m})=>f.createElement(Ox,{key:h.key||h.src,photo:h,layout:m,layoutOptions:n,renderPhoto:r,imageProps:i}))))):null}function WH({containerProps:e,children:t,containerRef:n}){return f.createElement("div",{ref:n,...e},t)}function HH(e){const{layout:t,renderContainer:n,children:r,containerRef:o,containerProps:{style:i,className:s,...l}={}}=e,u={className:qm("react-photo-album",`react-photo-album--${t}`,s),style:{display:"flex",flexWrap:"nowrap",justifyContent:"space-between",flexDirection:t==="rows"?"column":"row",...i},...l};return f.createElement(f.Fragment,null,(n??WH)({containerProps:u,containerRef:o,layout:t,children:r}))}function KH(e){const t=f.useRef(e);return(!e||!t.current||e.join()!==t.current.join())&&(t.current=e),t.current}function YH(e,{newContainerWidth:t,newScrollbarWidth:n}){const{containerWidth:r,scrollbarWidth:o}=e;return r!==void 0&&o!==void 0&&t!==void 0&&n!==void 0&&t>r&&t-r<=20&&n0){const r=[...t.filter(i=>i>0)].sort((i,s)=>s-i);r.push(Math.floor(r[r.length-1]/2));const o=n;n=r.find((i,s)=>i<=o||s===r.length-1)}return n}function XH(e,t){const[{containerWidth:n},r]=f.useReducer(YH,{containerWidth:t}),o=f.useRef(null),i=f.useRef();return{containerRef:f.useCallback(l=>{var u;(u=i.current)==null||u.disconnect(),i.current=void 0,o.current=l;const d=()=>r({newContainerWidth:GH(o.current,e),newScrollbarWidth:window.innerWidth-document.documentElement.clientWidth});d(),l&&typeof ResizeObserver<"u"&&(i.current=new ResizeObserver(d),i.current.observe(l))},[e]),containerWidth:n}}const ZH=Object.freeze([1200,600,300,0]);function Mx(e,t){return typeof e=="function"?e(t):e}function FP(e,t){return typeof e<"u"?Mx(e,t):void 0}function qH(e,t){const n=ZH.findIndex(r=>r<=t);return Mx(e[n>=0?n:0],t)}function fp(e,t,n,r=0){const o=FP(e,t);return Math.round(Math.max(o===void 0?qH(n,t):o,r))}function QH({layout:e,onClick:t,containerWidth:n,targetRowHeight:r,rowConstraints:o,columns:i,spacing:s,padding:l,sizes:u}){return{layout:e,onClick:t,containerWidth:n,columns:fp(i,n,[5,4,3,2],1),spacing:fp(s,n,[20,15,10,5]),padding:fp(l,n,[0,0,0,0,0]),targetRowHeight:fp(r,n,[d=>d/5,d=>d/4,d=>d/3,d=>d/2]),rowConstraints:FP(o,n),sizes:u}}function JH(e,t,n){const{photos:r,componentsProps:o}=e,i=Mx(o,t)||{};if(n){const{layout:s,spacing:l,padding:u,rowConstraints:d}=n;if(s==="rows"){const{singleRowMaxHeight:h}=d||{};if(h){const m=Math.floor(r.reduce((g,{width:y,height:x})=>g+y/x*h-2*u,u*r.length*2+l*(r.length-1)));m>0&&(i.containerProps=i.containerProps||{},i.containerProps.style={maxWidth:m,...i.containerProps.style})}}}return i}function eK(e,t,n){const{photos:r,layout:o,renderPhoto:i,renderRowContainer:s,renderColumnContainer:l}=e,u={photos:r,renderPhoto:i,componentsProps:t};return o==="rows"?f.createElement(MH,{layoutOptions:n,renderRowContainer:s,...u}):o==="columns"?f.createElement(UH,{layoutOptions:n,renderColumnContainer:l,...u}):f.createElement(VH,{layoutOptions:n,renderColumnContainer:l,...u})}function tK(e){const{photos:t,layout:n,renderContainer:r,defaultContainerWidth:o,breakpoints:i}=e,{containerRef:s,containerWidth:l}=XH(KH(i),o);if(!n||!["rows","columns","masonry"].includes(n)||!Array.isArray(t))return null;const u=l?QH({containerWidth:l,...e}):void 0,d=JH(e,l,u);return f.createElement(HH,{layout:n,containerRef:s,renderContainer:r,containerProps:d.containerProps},u&&eK(e,d,u))}function nK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h9.75m4.5-4.5v12m0 0l-3.75-3.75M17.25 21L21 17.25"}))}const rK=f.forwardRef(nK),oK=rK;function iK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 4.5h14.25M3 9h9.75M3 13.5h5.25m5.25-.75L17.25 9m0 0L21 12.75M17.25 9v12"}))}const sK=f.forwardRef(iK),aK=sK;function lK({title:e,titleId:t,...n},r){return f.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true",ref:r,"aria-labelledby":t},n),e?f.createElement("title",{id:t},e):null,f.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.042 21.672L13.684 16.6m0 0l-2.51 2.225.569-9.47 5.227 7.917-3.286-.672zM12 2.25V4.5m5.834.166l-1.591 1.591M20.25 10.5H18M7.757 14.743l-1.59 1.59M6 10.5H3.75m4.007-4.243l-1.59-1.59"}))}const cK=f.forwardRef(lK),uK=cK;function bi(e){return Array.isArray?Array.isArray(e):BP(e)==="[object Array]"}const dK=1/0;function fK(e){if(typeof e=="string")return e;let t=e+"";return t=="0"&&1/e==-dK?"-0":t}function pK(e){return e==null?"":fK(e)}function Lo(e){return typeof e=="string"}function jP(e){return typeof e=="number"}function hK(e){return e===!0||e===!1||mK(e)&&BP(e)=="[object Boolean]"}function zP(e){return typeof e=="object"}function mK(e){return zP(e)&&e!==null}function hr(e){return e!=null}function k0(e){return!e.trim().length}function BP(e){return e==null?e===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(e)}const gK="Incorrect 'index' type",vK=e=>`Invalid value for key ${e}`,yK=e=>`Pattern length exceeds max of ${e}.`,wK=e=>`Missing ${e} property in key`,xK=e=>`Property 'weight' in key '${e}' must be a positive integer`,a2=Object.prototype.hasOwnProperty;class bK{constructor(t){this._keys=[],this._keyMap={};let n=0;t.forEach(r=>{let o=UP(r);this._keys.push(o),this._keyMap[o.id]=o,n+=o.weight}),this._keys.forEach(r=>{r.weight/=n})}get(t){return this._keyMap[t]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function UP(e){let t=null,n=null,r=null,o=1,i=null;if(Lo(e)||bi(e))r=e,t=l2(e),n=h1(e);else{if(!a2.call(e,"name"))throw new Error(wK("name"));const s=e.name;if(r=s,a2.call(e,"weight")&&(o=e.weight,o<=0))throw new Error(xK(s));t=l2(s),n=h1(s),i=e.getFn}return{path:t,id:n,weight:o,src:r,getFn:i}}function l2(e){return bi(e)?e:e.split(".")}function h1(e){return bi(e)?e.join("."):e}function _K(e,t){let n=[],r=!1;const o=(i,s,l)=>{if(hr(i))if(!s[l])n.push(i);else{let u=s[l];const d=i[u];if(!hr(d))return;if(l===s.length-1&&(Lo(d)||jP(d)||hK(d)))n.push(pK(d));else if(bi(d)){r=!0;for(let h=0,m=d.length;he.score===t.score?e.idx{this._keysMap[n.id]=r})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Lo(this.docs[0])?this.docs.forEach((t,n)=>{this._addString(t,n)}):this.docs.forEach((t,n)=>{this._addObject(t,n)}),this.norm.clear())}add(t){const n=this.size();Lo(t)?this._addString(t,n):this._addObject(t,n)}removeAt(t){this.records.splice(t,1);for(let n=t,r=this.size();n{let s=o.getFn?o.getFn(t):this.getFn(t,o.path);if(hr(s)){if(bi(s)){let l=[];const u=[{nestedArrIndex:-1,value:s}];for(;u.length;){const{nestedArrIndex:d,value:h}=u.pop();if(hr(h))if(Lo(h)&&!k0(h)){let m={v:h,i:d,n:this.norm.get(h)};l.push(m)}else bi(h)&&h.forEach((m,g)=>{u.push({nestedArrIndex:g,value:m})})}r.$[i]=l}else if(Lo(s)&&!k0(s)){let l={v:s,n:this.norm.get(s)};r.$[i]=l}}}),this.records.push(r)}toJSON(){return{keys:this.keys,records:this.records}}}function VP(e,t,{getFn:n=He.getFn,fieldNormWeight:r=He.fieldNormWeight}={}){const o=new Nx({getFn:n,fieldNormWeight:r});return o.setKeys(e.map(UP)),o.setSources(t),o.create(),o}function TK(e,{getFn:t=He.getFn,fieldNormWeight:n=He.fieldNormWeight}={}){const{keys:r,records:o}=e,i=new Nx({getFn:t,fieldNormWeight:n});return i.setKeys(r),i.setIndexRecords(o),i}function pp(e,{errors:t=0,currentLocation:n=0,expectedLocation:r=0,distance:o=He.distance,ignoreLocation:i=He.ignoreLocation}={}){const s=t/e.length;if(i)return s;const l=Math.abs(r-n);return o?s+l/o:l?1:s}function PK(e=[],t=He.minMatchCharLength){let n=[],r=-1,o=-1,i=0;for(let s=e.length;i=t&&n.push([r,o]),r=-1)}return e[i-1]&&i-r>=t&&n.push([r,i-1]),n}const ea=32;function AK(e,t,n,{location:r=He.location,distance:o=He.distance,threshold:i=He.threshold,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,includeMatches:u=He.includeMatches,ignoreLocation:d=He.ignoreLocation}={}){if(t.length>ea)throw new Error(yK(ea));const h=t.length,m=e.length,g=Math.max(0,Math.min(r,m));let y=i,x=g;const _=l>1||u,C=_?Array(m):[];let S;for(;(S=e.indexOf(t,x))>-1;){let A=pp(t,{currentLocation:S,expectedLocation:g,distance:o,ignoreLocation:d});if(y=Math.min(A,y),x=S+h,_){let O=0;for(;O=V;U-=1){let te=U-1,L=n[e.charAt(te)];if(_&&(C[te]=+!!L),G[U]=(G[U+1]<<1|1)&L,A&&(G[U]|=(b[U+1]|b[U])<<1|1|b[U+1]),G[U]&P&&(E=pp(t,{errors:A,currentLocation:te,expectedLocation:g,distance:o,ignoreLocation:d}),E<=y)){if(y=E,x=te,x<=g)break;V=Math.max(1,2*g-x)}}if(pp(t,{errors:A+1,currentLocation:g,expectedLocation:g,distance:o,ignoreLocation:d})>y)break;b=G}const M={isMatch:x>=0,score:Math.max(.001,E)};if(_){const A=PK(C,l);A.length?u&&(M.indices=A):M.isMatch=!1}return M}function OK(e){let t={};for(let n=0,r=e.length;n{this.chunks.push({pattern:g,alphabet:OK(g),startIndex:y})},m=this.pattern.length;if(m>ea){let g=0;const y=m%ea,x=m-y;for(;g{const{isMatch:S,score:b,indices:E}=AK(t,x,_,{location:o+C,distance:i,threshold:s,findAllMatches:l,minMatchCharLength:u,includeMatches:r,ignoreLocation:d});S&&(g=!0),m+=b,S&&E&&(h=[...h,...E])});let y={isMatch:g,score:g?m/this.chunks.length:1};return g&&r&&(y.indices=h),y}}class Ds{constructor(t){this.pattern=t}static isMultiMatch(t){return c2(t,this.multiRegex)}static isSingleMatch(t){return c2(t,this.singleRegex)}search(){}}function c2(e,t){const n=e.match(t);return n?n[1]:null}class MK extends Ds{constructor(t){super(t)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(t){const n=t===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class NK extends Ds{constructor(t){super(t)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(t){const r=t.indexOf(this.pattern)===-1;return{isMatch:r,score:r?0:1,indices:[0,t.length-1]}}}class DK extends Ds{constructor(t){super(t)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(t){const n=t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class IK extends Ds{constructor(t){super(t)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(t){const n=!t.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class LK extends Ds{constructor(t){super(t)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(t){const n=t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[t.length-this.pattern.length,t.length-1]}}}class FK extends Ds{constructor(t){super(t)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(t){const n=!t.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,t.length-1]}}}class HP extends Ds{constructor(t,{location:n=He.location,threshold:r=He.threshold,distance:o=He.distance,includeMatches:i=He.includeMatches,findAllMatches:s=He.findAllMatches,minMatchCharLength:l=He.minMatchCharLength,isCaseSensitive:u=He.isCaseSensitive,ignoreLocation:d=He.ignoreLocation}={}){super(t),this._bitapSearch=new WP(t,{location:n,threshold:r,distance:o,includeMatches:i,findAllMatches:s,minMatchCharLength:l,isCaseSensitive:u,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(t){return this._bitapSearch.searchIn(t)}}class KP extends Ds{constructor(t){super(t)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(t){let n=0,r;const o=[],i=this.pattern.length;for(;(r=t.indexOf(this.pattern,n))>-1;)n=r+i,o.push([r,n-1]);const s=!!o.length;return{isMatch:s,score:s?0:1,indices:o}}}const m1=[MK,KP,DK,IK,FK,LK,NK,HP],u2=m1.length,jK=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,zK="|";function BK(e,t={}){return e.split(zK).map(n=>{let r=n.trim().split(jK).filter(i=>i&&!!i.trim()),o=[];for(let i=0,s=r.length;i!!(e[jh.AND]||e[jh.OR]),HK=e=>!!e[y1.PATH],KK=e=>!bi(e)&&zP(e)&&!w1(e),d2=e=>({[jh.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function YP(e,t,{auto:n=!0}={}){const r=o=>{let i=Object.keys(o);const s=HK(o);if(!s&&i.length>1&&!w1(o))return r(d2(o));if(KK(o)){const u=s?o[y1.PATH]:i[0],d=s?o[y1.PATTERN]:o[u];if(!Lo(d))throw new Error(vK(u));const h={keyId:h1(u),pattern:d};return n&&(h.searcher=v1(d,t)),h}let l={children:[],operator:i[0]};return i.forEach(u=>{const d=o[u];bi(d)&&d.forEach(h=>{l.children.push(r(h))})}),l};return w1(e)||(e=d2(e)),r(e)}function YK(e,{ignoreFieldNorm:t=He.ignoreFieldNorm}){e.forEach(n=>{let r=1;n.matches.forEach(({key:o,norm:i,score:s})=>{const l=o?o.weight:null;r*=Math.pow(s===0&&l?Number.EPSILON:s,(l||1)*(t?1:i))}),n.score=r})}function GK(e,t){const n=e.matches;t.matches=[],hr(n)&&n.forEach(r=>{if(!hr(r.indices)||!r.indices.length)return;const{indices:o,value:i}=r;let s={indices:o,value:i};r.key&&(s.key=r.key.src),r.idx>-1&&(s.refIndex=r.idx),t.matches.push(s)})}function XK(e,t){t.score=e.score}function ZK(e,t,{includeMatches:n=He.includeMatches,includeScore:r=He.includeScore}={}){const o=[];return n&&o.push(GK),r&&o.push(XK),e.map(i=>{const{idx:s}=i,l={item:t[s],refIndex:s};return o.length&&o.forEach(u=>{u(i,l)}),l})}class _c{constructor(t,n={},r){this.options={...He,...n},this.options.useExtendedSearch,this._keyStore=new bK(this.options.keys),this.setCollection(t,r)}setCollection(t,n){if(this._docs=t,n&&!(n instanceof Nx))throw new Error(gK);this._myIndex=n||VP(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(t){hr(t)&&(this._docs.push(t),this._myIndex.add(t))}remove(t=()=>!1){const n=[];for(let r=0,o=this._docs.length;r-1&&(u=u.slice(0,n)),ZK(u,this._docs,{includeMatches:r,includeScore:o})}_searchStringList(t){const n=v1(t,this.options),{records:r}=this._myIndex,o=[];return r.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=n.searchIn(i);u&&o.push({item:i,idx:s,matches:[{score:d,value:i,norm:l,indices:h}]})}),o}_searchLogical(t){const n=YP(t,this.options),r=(l,u,d)=>{if(!l.children){const{keyId:m,searcher:g}=l,y=this._findMatches({key:this._keyStore.get(m),value:this._myIndex.getValueForItemAtKeyId(u,m),searcher:g});return y&&y.length?[{idx:d,item:u,matches:y}]:[]}const h=[];for(let m=0,g=l.children.length;m{if(hr(l)){let d=r(n,l,u);d.length&&(i[u]||(i[u]={idx:u,item:l,matches:[]},s.push(i[u])),d.forEach(({matches:h})=>{i[u].matches.push(...h)}))}}),s}_searchObjectList(t){const n=v1(t,this.options),{keys:r,records:o}=this._myIndex,i=[];return o.forEach(({$:s,i:l})=>{if(!hr(s))return;let u=[];r.forEach((d,h)=>{u.push(...this._findMatches({key:d,value:s[h],searcher:n}))}),u.length&&i.push({idx:l,item:s,matches:u})}),i}_findMatches({key:t,value:n,searcher:r}){if(!hr(n))return[];let o=[];if(bi(n))n.forEach(({v:i,i:s,n:l})=>{if(!hr(i))return;const{isMatch:u,score:d,indices:h}=r.searchIn(i);u&&o.push({score:d,key:t,value:i,idx:s,norm:l,indices:h})});else{const{v:i,n:s}=n,{isMatch:l,score:u,indices:d}=r.searchIn(i);l&&o.push({score:u,key:t,value:i,norm:s,indices:d})}return o}}_c.version="7.0.0";_c.createIndex=VP;_c.parseIndex=TK;_c.config=He;_c.parseQuery=YP;WK(VK);function zd(e){const t=e+"CollectionProvider",[n,r]=An(t),[o,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),s=y=>{const{scope:x,children:_}=y,C=Fe.useRef(null),S=Fe.useRef(new Map).current;return Fe.createElement(o,{scope:x,itemMap:S,collectionRef:C},_)},l=e+"CollectionSlot",u=Fe.forwardRef((y,x)=>{const{scope:_,children:C}=y,S=i(l,_),b=Be(x,S.collectionRef);return Fe.createElement(Wo,{ref:b},C)}),d=e+"CollectionItemSlot",h="data-radix-collection-item",m=Fe.forwardRef((y,x)=>{const{scope:_,children:C,...S}=y,b=Fe.useRef(null),E=Be(x,b),k=i(d,_);return Fe.useEffect(()=>(k.itemMap.set(b,{ref:b,...S}),()=>void k.itemMap.delete(b))),Fe.createElement(Wo,{[h]:"",ref:E},C)});function g(y){const x=i(e+"CollectionConsumer",y);return Fe.useCallback(()=>{const C=x.collectionRef.current;if(!C)return[];const S=Array.from(C.querySelectorAll(`[${h}]`));return Array.from(x.itemMap.values()).sort((k,P)=>S.indexOf(k.ref.current)-S.indexOf(P.ref.current))},[x.collectionRef,x.itemMap])}return[{Provider:s,Slot:u,ItemSlot:m},g,r]}const qK=f.createContext(void 0);function Sc(e){const t=f.useContext(qK);return e||t||"ltr"}const R0="rovingFocusGroup.onEntryFocus",QK={bubbles:!1,cancelable:!0},Dx="RovingFocusGroup",[x1,GP,JK]=zd(Dx),[eY,Qm]=An(Dx,[JK]),[tY,nY]=eY(Dx),rY=f.forwardRef((e,t)=>f.createElement(x1.Provider,{scope:e.__scopeRovingFocusGroup},f.createElement(x1.Slot,{scope:e.__scopeRovingFocusGroup},f.createElement(oY,Y({},e,{ref:t}))))),oY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:o=!1,dir:i,currentTabStopId:s,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,...h}=e,m=f.useRef(null),g=Be(t,m),y=Sc(i),[x=null,_]=Zr({prop:s,defaultProp:l,onChange:u}),[C,S]=f.useState(!1),b=Ft(d),E=GP(n),k=f.useRef(!1),[P,M]=f.useState(0);return f.useEffect(()=>{const A=m.current;if(A)return A.addEventListener(R0,b),()=>A.removeEventListener(R0,b)},[b]),f.createElement(tY,{scope:n,orientation:r,dir:y,loop:o,currentTabStopId:x,onItemFocus:f.useCallback(A=>_(A),[_]),onItemShiftTab:f.useCallback(()=>S(!0),[]),onFocusableItemAdd:f.useCallback(()=>M(A=>A+1),[]),onFocusableItemRemove:f.useCallback(()=>M(A=>A-1),[])},f.createElement(Pe.div,Y({tabIndex:C||P===0?-1:0,"data-orientation":r},h,{ref:g,style:{outline:"none",...e.style},onMouseDown:ue(e.onMouseDown,()=>{k.current=!0}),onFocus:ue(e.onFocus,A=>{const O=!k.current;if(A.target===A.currentTarget&&O&&!C){const F=new CustomEvent(R0,QK);if(A.currentTarget.dispatchEvent(F),!F.defaultPrevented){const V=E().filter(te=>te.focusable),J=V.find(te=>te.active),G=V.find(te=>te.id===x),U=[J,G,...V].filter(Boolean).map(te=>te.ref.current);XP(U)}}k.current=!1}),onBlur:ue(e.onBlur,()=>S(!1))})))}),iY="RovingFocusGroupItem",sY=f.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:o=!1,tabStopId:i,...s}=e,l=nr(),u=i||l,d=nY(iY,n),h=d.currentTabStopId===u,m=GP(n),{onFocusableItemAdd:g,onFocusableItemRemove:y}=d;return f.useEffect(()=>{if(r)return g(),()=>y()},[r,g,y]),f.createElement(x1.ItemSlot,{scope:n,id:u,focusable:r,active:o},f.createElement(Pe.span,Y({tabIndex:h?0:-1,"data-orientation":d.orientation},s,{ref:t,onMouseDown:ue(e.onMouseDown,x=>{r?d.onItemFocus(u):x.preventDefault()}),onFocus:ue(e.onFocus,()=>d.onItemFocus(u)),onKeyDown:ue(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){d.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const _=cY(x,d.orientation,d.dir);if(_!==void 0){x.preventDefault();let S=m().filter(b=>b.focusable).map(b=>b.ref.current);if(_==="last")S.reverse();else if(_==="prev"||_==="next"){_==="prev"&&S.reverse();const b=S.indexOf(x.currentTarget);S=d.loop?uY(S,b+1):S.slice(b+1)}setTimeout(()=>XP(S))}})})))}),aY={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function lY(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function cY(e,t,n){const r=lY(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return aY[r]}function XP(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function uY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const ZP=rY,qP=sY,QP="Tabs",[dY,wte]=An(QP,[Qm]),JP=Qm(),[fY,Ix]=dY(QP),pY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,onValueChange:o,defaultValue:i,orientation:s="horizontal",dir:l,activationMode:u="automatic",...d}=e,h=Sc(l),[m,g]=Zr({prop:r,onChange:o,defaultProp:i});return f.createElement(fY,{scope:n,baseId:nr(),value:m,onValueChange:g,orientation:s,dir:h,activationMode:u},f.createElement(Pe.div,Y({dir:h,"data-orientation":s},d,{ref:t})))}),hY="TabsList",mY=f.forwardRef((e,t)=>{const{__scopeTabs:n,loop:r=!0,...o}=e,i=Ix(hY,n),s=JP(n);return f.createElement(ZP,Y({asChild:!0},s,{orientation:i.orientation,dir:i.dir,loop:r}),f.createElement(Pe.div,Y({role:"tablist","aria-orientation":i.orientation},o,{ref:t})))}),gY="TabsTrigger",vY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,disabled:o=!1,...i}=e,s=Ix(gY,n),l=JP(n),u=e5(s.baseId,r),d=t5(s.baseId,r),h=r===s.value;return f.createElement(qP,Y({asChild:!0},l,{focusable:!o,active:h}),f.createElement(Pe.button,Y({type:"button",role:"tab","aria-selected":h,"aria-controls":d,"data-state":h?"active":"inactive","data-disabled":o?"":void 0,disabled:o,id:u},i,{ref:t,onMouseDown:ue(e.onMouseDown,m=>{!o&&m.button===0&&m.ctrlKey===!1?s.onValueChange(r):m.preventDefault()}),onKeyDown:ue(e.onKeyDown,m=>{[" ","Enter"].includes(m.key)&&s.onValueChange(r)}),onFocus:ue(e.onFocus,()=>{const m=s.activationMode!=="manual";!h&&!o&&m&&s.onValueChange(r)})})))}),yY="TabsContent",wY=f.forwardRef((e,t)=>{const{__scopeTabs:n,value:r,forceMount:o,children:i,...s}=e,l=Ix(yY,n),u=e5(l.baseId,r),d=t5(l.baseId,r),h=r===l.value,m=f.useRef(h);return f.useEffect(()=>{const g=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(g)},[]),f.createElement(bn,{present:o||h},({present:g})=>f.createElement(Pe.div,Y({"data-state":h?"active":"inactive","data-orientation":l.orientation,role:"tabpanel","aria-labelledby":u,hidden:!g,id:d,tabIndex:0},s,{ref:t,style:{...e.style,animationDuration:m.current?"0s":void 0}}),g&&i))});function e5(e,t){return`${e}-trigger-${t}`}function t5(e,t){return`${e}-content-${t}`}const xY=pY,n5=mY,r5=vY,o5=wY,i5=xY,Lx=f.forwardRef(({className:e,...t},n)=>v.jsx(n5,{ref:n,className:Ce("inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",e),tabIndex:-1,...t}));Lx.displayName=n5.displayName;const sa=f.forwardRef(({className:e,...t},n)=>v.jsx(r5,{ref:n,className:Ce("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",e),tabIndex:-1,...t}));sa.displayName=r5.displayName;const mu=f.forwardRef(({className:e,...t},n)=>v.jsx(o5,{ref:n,className:Ce("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",e),tabIndex:-1,...t}));mu.displayName=o5.displayName;function id(e,[t,n]){return Math.min(n,Math.max(t,e))}function Fx(e){const t=f.useRef({value:e,previous:e});return f.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}const bY=[" ","Enter","ArrowUp","ArrowDown"],_Y=[" ","Enter"],Jm="Select",[eg,tg,SY]=zd(Jm),[Ec,xte]=An(Jm,[SY,Ns]),jx=Ns(),[EY,Oa]=Ec(Jm),[CY,$Y]=Ec(Jm),kY=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:i,value:s,defaultValue:l,onValueChange:u,dir:d,name:h,autoComplete:m,disabled:g,required:y}=e,x=jx(t),[_,C]=f.useState(null),[S,b]=f.useState(null),[E,k]=f.useState(!1),P=Sc(d),[M=!1,A]=Zr({prop:r,defaultProp:o,onChange:i}),[O,F]=Zr({prop:s,defaultProp:l,onChange:u}),V=f.useRef(null),J=_?!!_.closest("form"):!0,[G,ae]=f.useState(new Set),U=Array.from(G).map(te=>te.props.value).join(";");return f.createElement(Od,x,f.createElement(EY,{required:y,scope:t,trigger:_,onTriggerChange:C,valueNode:S,onValueNodeChange:b,valueNodeHasChildren:E,onValueNodeHasChildrenChange:k,contentId:nr(),value:O,onValueChange:F,open:M,onOpenChange:A,dir:P,triggerPointerDownPosRef:V,disabled:g},f.createElement(eg.Provider,{scope:t},f.createElement(CY,{scope:e.__scopeSelect,onNativeOptionAdd:f.useCallback(te=>{ae(L=>new Set(L).add(te))},[]),onNativeOptionRemove:f.useCallback(te=>{ae(L=>{const ie=new Set(L);return ie.delete(te),ie})},[])},n)),J?f.createElement(u5,{key:U,"aria-hidden":!0,required:y,tabIndex:-1,name:h,autoComplete:m,value:O,onChange:te=>F(te.target.value),disabled:g},O===void 0?f.createElement("option",{value:""}):null,Array.from(G)):null))},RY="SelectTrigger",TY=f.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,i=jx(n),s=Oa(RY,n),l=s.disabled||r,u=Be(t,s.onTriggerChange),d=tg(n),[h,m,g]=d5(x=>{const _=d().filter(b=>!b.disabled),C=_.find(b=>b.value===s.value),S=f5(_,x,C);S!==void 0&&s.onValueChange(S.value)}),y=()=>{l||(s.onOpenChange(!0),g())};return f.createElement(zm,Y({asChild:!0},i),f.createElement(Pe.button,Y({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:l,"data-disabled":l?"":void 0,"data-placeholder":c5(s.value)?"":void 0},o,{ref:u,onClick:ue(o.onClick,x=>{x.currentTarget.focus()}),onPointerDown:ue(o.onPointerDown,x=>{const _=x.target;_.hasPointerCapture(x.pointerId)&&_.releasePointerCapture(x.pointerId),x.button===0&&x.ctrlKey===!1&&(y(),s.triggerPointerDownPosRef.current={x:Math.round(x.pageX),y:Math.round(x.pageY)},x.preventDefault())}),onKeyDown:ue(o.onKeyDown,x=>{const _=h.current!=="";!(x.ctrlKey||x.altKey||x.metaKey)&&x.key.length===1&&m(x.key),!(_&&x.key===" ")&&bY.includes(x.key)&&(y(),x.preventDefault())})})))}),PY="SelectValue",AY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:i,placeholder:s="",...l}=e,u=Oa(PY,n),{onValueNodeHasChildrenChange:d}=u,h=i!==void 0,m=Be(t,u.onValueNodeChange);return Pn(()=>{d(h)},[d,h]),f.createElement(Pe.span,Y({},l,{ref:m,style:{pointerEvents:"none"}}),c5(u.value)?f.createElement(f.Fragment,null,s):i)}),OY=f.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return f.createElement(Pe.span,Y({"aria-hidden":!0},o,{ref:t}),r||"▼")}),MY=e=>f.createElement(Md,Y({asChild:!0},e)),ic="SelectContent",NY=f.forwardRef((e,t)=>{const n=Oa(ic,e.__scopeSelect),[r,o]=f.useState();if(Pn(()=>{o(new DocumentFragment)},[]),!n.open){const i=r;return i?Os.createPortal(f.createElement(s5,{scope:e.__scopeSelect},f.createElement(eg.Slot,{scope:e.__scopeSelect},f.createElement("div",null,e.children))),i):null}return f.createElement(DY,Y({},e,{ref:t}))}),ai=10,[s5,Ma]=Ec(ic),DY=f.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:i,onPointerDownOutside:s,side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C,...S}=e,b=Oa(ic,n),[E,k]=f.useState(null),[P,M]=f.useState(null),A=Be(t,fe=>k(fe)),[O,F]=f.useState(null),[V,J]=f.useState(null),G=tg(n),[ae,U]=f.useState(!1),te=f.useRef(!1);f.useEffect(()=>{if(E)return Xm(E)},[E]),Km();const L=f.useCallback(fe=>{const[xe,...$e]=G().map(je=>je.ref.current),[Ae]=$e.slice(-1),Oe=document.activeElement;for(const je of fe)if(je===Oe||(je==null||je.scrollIntoView({block:"nearest"}),je===xe&&P&&(P.scrollTop=0),je===Ae&&P&&(P.scrollTop=P.scrollHeight),je==null||je.focus(),document.activeElement!==Oe))return},[G,P]),ie=f.useCallback(()=>L([O,E]),[L,O,E]);f.useEffect(()=>{ae&&ie()},[ae,ie]);const{onOpenChange:K,triggerPointerDownPosRef:Q}=b;f.useEffect(()=>{if(E){let fe={x:0,y:0};const xe=Ae=>{var Oe,je,Ot,ct;fe={x:Math.abs(Math.round(Ae.pageX)-((Oe=(je=Q.current)===null||je===void 0?void 0:je.x)!==null&&Oe!==void 0?Oe:0)),y:Math.abs(Math.round(Ae.pageY)-((Ot=(ct=Q.current)===null||ct===void 0?void 0:ct.y)!==null&&Ot!==void 0?Ot:0))}},$e=Ae=>{fe.x<=10&&fe.y<=10?Ae.preventDefault():E.contains(Ae.target)||K(!1),document.removeEventListener("pointermove",xe),Q.current=null};return Q.current!==null&&(document.addEventListener("pointermove",xe),document.addEventListener("pointerup",$e,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",xe),document.removeEventListener("pointerup",$e,{capture:!0})}}},[E,K,Q]),f.useEffect(()=>{const fe=()=>K(!1);return window.addEventListener("blur",fe),window.addEventListener("resize",fe),()=>{window.removeEventListener("blur",fe),window.removeEventListener("resize",fe)}},[K]);const[W,le]=d5(fe=>{const xe=G().filter(Oe=>!Oe.disabled),$e=xe.find(Oe=>Oe.ref.current===document.activeElement),Ae=f5(xe,fe,$e);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ge=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&(F(fe),Ae&&(te.current=!0))},[b.value]),Ve=f.useCallback(()=>E==null?void 0:E.focus(),[E]),Ue=f.useCallback((fe,xe,$e)=>{const Ae=!te.current&&!$e;(b.value!==void 0&&b.value===xe||Ae)&&J(fe)},[b.value]),We=r==="popper"?f2:IY,Me=We===f2?{side:l,sideOffset:u,align:d,alignOffset:h,arrowPadding:m,collisionBoundary:g,collisionPadding:y,sticky:x,hideWhenDetached:_,avoidCollisions:C}:{};return f.createElement(s5,{scope:n,content:E,viewport:P,onViewportChange:M,itemRefCallback:ge,selectedItem:O,onItemLeave:Ve,itemTextRefCallback:Ue,focusSelectedItem:ie,selectedItemText:V,position:r,isPositioned:ae,searchRef:W},f.createElement(Gm,{as:Wo,allowPinchZoom:!0},f.createElement(Hm,{asChild:!0,trapped:b.open,onMountAutoFocus:fe=>{fe.preventDefault()},onUnmountAutoFocus:ue(o,fe=>{var xe;(xe=b.trigger)===null||xe===void 0||xe.focus({preventScroll:!0}),fe.preventDefault()})},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:s,onFocusOutside:fe=>fe.preventDefault(),onDismiss:()=>b.onOpenChange(!1)},f.createElement(We,Y({role:"listbox",id:b.contentId,"data-state":b.open?"open":"closed",dir:b.dir,onContextMenu:fe=>fe.preventDefault()},S,Me,{onPlaced:()=>U(!0),ref:A,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:ue(S.onKeyDown,fe=>{const xe=fe.ctrlKey||fe.altKey||fe.metaKey;if(fe.key==="Tab"&&fe.preventDefault(),!xe&&fe.key.length===1&&le(fe.key),["ArrowUp","ArrowDown","Home","End"].includes(fe.key)){let Ae=G().filter(Oe=>!Oe.disabled).map(Oe=>Oe.ref.current);if(["ArrowUp","End"].includes(fe.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(fe.key)){const Oe=fe.target,je=Ae.indexOf(Oe);Ae=Ae.slice(je+1)}setTimeout(()=>L(Ae)),fe.preventDefault()}})}))))))}),IY=f.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,i=Oa(ic,n),s=Ma(ic,n),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Be(t,A=>h(A)),g=tg(n),y=f.useRef(!1),x=f.useRef(!0),{viewport:_,selectedItem:C,selectedItemText:S,focusSelectedItem:b}=s,E=f.useCallback(()=>{if(i.trigger&&i.valueNode&&l&&d&&_&&C&&S){const A=i.trigger.getBoundingClientRect(),O=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),V=S.getBoundingClientRect();if(i.dir!=="rtl"){const Oe=V.left-O.left,je=F.left-Oe,Ot=A.left-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.left=gt+"px"}else{const Oe=O.right-V.right,je=window.innerWidth-F.right-Oe,Ot=window.innerWidth-A.right-je,ct=A.width+Ot,Kt=Math.max(ct,O.width),Er=window.innerWidth-ai,gt=id(je,[ai,Er-Kt]);l.style.minWidth=ct+"px",l.style.right=gt+"px"}const J=g(),G=window.innerHeight-ai*2,ae=_.scrollHeight,U=window.getComputedStyle(d),te=parseInt(U.borderTopWidth,10),L=parseInt(U.paddingTop,10),ie=parseInt(U.borderBottomWidth,10),K=parseInt(U.paddingBottom,10),Q=te+L+ae+K+ie,W=Math.min(C.offsetHeight*5,Q),le=window.getComputedStyle(_),ge=parseInt(le.paddingTop,10),Ve=parseInt(le.paddingBottom,10),Ue=A.top+A.height/2-ai,We=G-Ue,Me=C.offsetHeight/2,fe=C.offsetTop+Me,xe=te+L+fe,$e=Q-xe;if(xe<=Ue){const Oe=C===J[J.length-1].ref.current;l.style.bottom="0px";const je=d.clientHeight-_.offsetTop-_.offsetHeight,Ot=Math.max(We,Me+(Oe?Ve:0)+je+ie),ct=xe+Ot;l.style.height=ct+"px"}else{const Oe=C===J[0].ref.current;l.style.top="0px";const Ot=Math.max(Ue,te+_.offsetTop+(Oe?ge:0)+Me)+$e;l.style.height=Ot+"px",_.scrollTop=xe-Ue+_.offsetTop}l.style.margin=`${ai}px 0`,l.style.minHeight=W+"px",l.style.maxHeight=G+"px",r==null||r(),requestAnimationFrame(()=>y.current=!0)}},[g,i.trigger,i.valueNode,l,d,_,C,S,i.dir,r]);Pn(()=>E(),[E]);const[k,P]=f.useState();Pn(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const M=f.useCallback(A=>{A&&x.current===!0&&(E(),b==null||b(),x.current=!1)},[E,b]);return f.createElement(LY,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:y,onScrollButtonChange:M},f.createElement("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k}},f.createElement(Pe.div,Y({},o,{ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}}))))}),f2=f.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=ai,...i}=e,s=jx(n);return f.createElement(Bm,Y({},s,i,{ref:t,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)"}}))}),[LY,zx]=Ec(ic,{}),p2="SelectViewport",FY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Ma(p2,n),i=zx(p2,n),s=Be(t,o.onViewportChange),l=f.useRef(0);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(eg.Slot,{scope:n},f.createElement(Pe.div,Y({"data-radix-select-viewport":"",role:"presentation"},r,{ref:s,style:{position:"relative",flex:1,overflow:"auto",...r.style},onScroll:ue(r.onScroll,u=>{const d=u.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&h){const g=Math.abs(l.current-d.scrollTop);if(g>0){const y=window.innerHeight-ai*2,x=parseFloat(h.style.minHeight),_=parseFloat(h.style.height),C=Math.max(x,_);if(C0?E:0,h.style.justifyContent="flex-end")}}}l.current=d.scrollTop})}))))}),jY="SelectGroup",[zY,BY]=Ec(jY),UY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=nr();return f.createElement(zY,{scope:n,id:o},f.createElement(Pe.div,Y({role:"group","aria-labelledby":o},r,{ref:t})))}),VY="SelectLabel",WY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=BY(VY,n);return f.createElement(Pe.div,Y({id:o.id},r,{ref:t}))}),b1="SelectItem",[HY,a5]=Ec(b1),KY=f.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:i,...s}=e,l=Oa(b1,n),u=Ma(b1,n),d=l.value===r,[h,m]=f.useState(i??""),[g,y]=f.useState(!1),x=Be(t,S=>{var b;return(b=u.itemRefCallback)===null||b===void 0?void 0:b.call(u,S,r,o)}),_=nr(),C=()=>{o||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A 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 f.createElement(HY,{scope:n,value:r,disabled:o,textId:_,isSelected:d,onItemTextChange:f.useCallback(S=>{m(b=>{var E;return b||((E=S==null?void 0:S.textContent)!==null&&E!==void 0?E:"").trim()})},[])},f.createElement(eg.ItemSlot,{scope:n,value:r,disabled:o,textValue:h},f.createElement(Pe.div,Y({role:"option","aria-labelledby":_,"data-highlighted":g?"":void 0,"aria-selected":d&&g,"data-state":d?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1},s,{ref:x,onFocus:ue(s.onFocus,()=>y(!0)),onBlur:ue(s.onBlur,()=>y(!1)),onPointerUp:ue(s.onPointerUp,C),onPointerMove:ue(s.onPointerMove,S=>{if(o){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}else S.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ue(s.onPointerLeave,S=>{if(S.currentTarget===document.activeElement){var b;(b=u.onItemLeave)===null||b===void 0||b.call(u)}}),onKeyDown:ue(s.onKeyDown,S=>{var b;((b=u.searchRef)===null||b===void 0?void 0:b.current)!==""&&S.key===" "||(_Y.includes(S.key)&&C(),S.key===" "&&S.preventDefault())})}))))}),hp="SelectItemText",YY=f.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...i}=e,s=Oa(hp,n),l=Ma(hp,n),u=a5(hp,n),d=$Y(hp,n),[h,m]=f.useState(null),g=Be(t,S=>m(S),u.onItemTextChange,S=>{var b;return(b=l.itemTextRefCallback)===null||b===void 0?void 0:b.call(l,S,u.value,u.disabled)}),y=h==null?void 0:h.textContent,x=f.useMemo(()=>f.createElement("option",{key:u.value,value:u.value,disabled:u.disabled},y),[u.disabled,u.value,y]),{onNativeOptionAdd:_,onNativeOptionRemove:C}=d;return Pn(()=>(_(x),()=>C(x)),[_,C,x]),f.createElement(f.Fragment,null,f.createElement(Pe.span,Y({id:u.textId},i,{ref:g})),u.isSelected&&s.valueNode&&!s.valueNodeHasChildren?Os.createPortal(i.children,s.valueNode):null)}),GY="SelectItemIndicator",XY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return a5(GY,n).isSelected?f.createElement(Pe.span,Y({"aria-hidden":!0},r,{ref:t})):null}),h2="SelectScrollUpButton",ZY=f.forwardRef((e,t)=>{const n=Ma(h2,e.__scopeSelect),r=zx(h2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollTop>0;i(h)};var l=d;const u=n.viewport;return d(),u.addEventListener("scroll",d),()=>u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}})):null}),m2="SelectScrollDownButton",qY=f.forwardRef((e,t)=>{const n=Ma(m2,e.__scopeSelect),r=zx(m2,e.__scopeSelect),[o,i]=f.useState(!1),s=Be(t,r.onScrollButtonChange);return Pn(()=>{if(n.viewport&&n.isPositioned){let d=function(){const h=u.scrollHeight-u.clientHeight,m=Math.ceil(u.scrollTop)u.removeEventListener("scroll",d)}},[n.viewport,n.isPositioned]),o?f.createElement(l5,Y({},e,{ref:s,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}})):null}),l5=f.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,i=Ma("SelectScrollButton",n),s=f.useRef(null),l=tg(n),u=f.useCallback(()=>{s.current!==null&&(window.clearInterval(s.current),s.current=null)},[]);return f.useEffect(()=>()=>u(),[u]),Pn(()=>{var d;const h=l().find(m=>m.ref.current===document.activeElement);h==null||(d=h.ref.current)===null||d===void 0||d.scrollIntoView({block:"nearest"})},[l]),f.createElement(Pe.div,Y({"aria-hidden":!0},o,{ref:t,style:{flexShrink:0,...o.style},onPointerDown:ue(o.onPointerDown,()=>{s.current===null&&(s.current=window.setInterval(r,50))}),onPointerMove:ue(o.onPointerMove,()=>{var d;(d=i.onItemLeave)===null||d===void 0||d.call(i),s.current===null&&(s.current=window.setInterval(r,50))}),onPointerLeave:ue(o.onPointerLeave,()=>{u()})}))}),QY=f.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return f.createElement(Pe.div,Y({"aria-hidden":!0},r,{ref:t}))});function c5(e){return e===""||e===void 0}const u5=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=f.useRef(null),i=Be(t,o),s=Fx(n);return f.useEffect(()=>{const l=o.current,u=window.HTMLSelectElement.prototype,h=Object.getOwnPropertyDescriptor(u,"value").set;if(s!==n&&h){const m=new Event("change",{bubbles:!0});h.call(l,n),l.dispatchEvent(m)}},[s,n]),f.createElement(Um,{asChild:!0},f.createElement("select",Y({},r,{ref:i,defaultValue:n})))});u5.displayName="BubbleSelect";function d5(e){const t=Ft(e),n=f.useRef(""),r=f.useRef(0),o=f.useCallback(s=>{const l=n.current+s;t(l),function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))}(l)},[t]),i=f.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,i]}function f5(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=JY(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.textValue.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function JY(e,t){return e.map((n,r)=>e[(t+r)%e.length])}const eG=kY,p5=TY,tG=AY,nG=OY,rG=MY,h5=NY,oG=FY,iG=UY,m5=WY,g5=KY,sG=YY,aG=XY,v5=ZY,y5=qY,w5=QY,aa=eG,wl=iG,la=tG,ls=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(p5,{ref:r,className:Ce("flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),tabIndex:-1,...n,children:[t,v.jsx(nG,{asChild:!0,children:v.jsx(Xj,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=p5.displayName;const x5=f.forwardRef(({className:e,...t},n)=>v.jsx(v5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(nz,{})}));x5.displayName=v5.displayName;const b5=f.forwardRef(({className:e,...t},n)=>v.jsx(y5,{ref:n,className:Ce("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Qj,{})}));b5.displayName=y5.displayName;const cs=f.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>v.jsx(rG,{children:v.jsxs(h5,{ref:o,className:Ce("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,onCloseAutoFocus:i=>i.preventDefault(),...r,children:[v.jsx(x5,{}),v.jsx(oG,{className:Ce("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),v.jsx(b5,{})]})}));cs.displayName=h5.displayName;const lG=f.forwardRef(({className:e,...t},n)=>v.jsx(m5,{ref:n,className:Ce("px-2 py-1.5 text-sm font-semibold",e),...t}));lG.displayName=m5.displayName;const us=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(g5,{ref:r,className:Ce("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute right-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(aG,{children:v.jsx(vT,{className:"h-4 w-4"})})}),v.jsx(sG,{children:t})]}));us.displayName=g5.displayName;const cG=f.forwardRef(({className:e,...t},n)=>v.jsx(w5,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));cG.displayName=w5.displayName;function uG(e,t){return f.useReducer((n,r)=>{const o=t[n][r];return o??n},e)}const _5="ScrollArea",[S5,bte]=An(_5),[dG,qr]=S5(_5),fG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:o,scrollHideDelay:i=600,...s}=e,[l,u]=f.useState(null),[d,h]=f.useState(null),[m,g]=f.useState(null),[y,x]=f.useState(null),[_,C]=f.useState(null),[S,b]=f.useState(0),[E,k]=f.useState(0),[P,M]=f.useState(!1),[A,O]=f.useState(!1),F=Be(t,J=>u(J)),V=Sc(o);return f.createElement(dG,{scope:n,type:r,dir:V,scrollHideDelay:i,scrollArea:l,viewport:d,onViewportChange:h,content:m,onContentChange:g,scrollbarX:y,onScrollbarXChange:x,scrollbarXEnabled:P,onScrollbarXEnabledChange:M,scrollbarY:_,onScrollbarYChange:C,scrollbarYEnabled:A,onScrollbarYEnabledChange:O,onCornerWidthChange:b,onCornerHeightChange:k},f.createElement(Pe.div,Y({dir:V},s,{ref:F,style:{position:"relative","--radix-scroll-area-corner-width":S+"px","--radix-scroll-area-corner-height":E+"px",...e.style}})))}),pG="ScrollAreaViewport",hG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,children:r,...o}=e,i=qr(pG,n),s=f.useRef(null),l=Be(t,s,i.onViewportChange);return f.createElement(f.Fragment,null,f.createElement("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}"}}),f.createElement(Pe.div,Y({"data-radix-scroll-area-viewport":""},o,{ref:l,style:{overflowX:i.scrollbarXEnabled?"scroll":"hidden",overflowY:i.scrollbarYEnabled?"scroll":"hidden",...e.style}}),f.createElement("div",{ref:i.onContentChange,style:{minWidth:"100%",display:"table"}},r)))}),$i="ScrollAreaScrollbar",E5=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:s}=o,l=e.orientation==="horizontal";return f.useEffect(()=>(l?i(!0):s(!0),()=>{l?i(!1):s(!1)}),[l,i,s]),o.type==="hover"?f.createElement(mG,Y({},r,{ref:t,forceMount:n})):o.type==="scroll"?f.createElement(gG,Y({},r,{ref:t,forceMount:n})):o.type==="auto"?f.createElement(C5,Y({},r,{ref:t,forceMount:n})):o.type==="always"?f.createElement(Bx,Y({},r,{ref:t})):null}),mG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),[i,s]=f.useState(!1);return f.useEffect(()=>{const l=o.scrollArea;let u=0;if(l){const d=()=>{window.clearTimeout(u),s(!0)},h=()=>{u=window.setTimeout(()=>s(!1),o.scrollHideDelay)};return l.addEventListener("pointerenter",d),l.addEventListener("pointerleave",h),()=>{window.clearTimeout(u),l.removeEventListener("pointerenter",d),l.removeEventListener("pointerleave",h)}}},[o.scrollArea,o.scrollHideDelay]),f.createElement(bn,{present:n||i},f.createElement(C5,Y({"data-state":i?"visible":"hidden"},r,{ref:t})))}),gG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=qr($i,e.__scopeScrollArea),i=e.orientation==="horizontal",s=rg(()=>u("SCROLL_END"),100),[l,u]=uG("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 f.useEffect(()=>{if(l==="idle"){const d=window.setTimeout(()=>u("HIDE"),o.scrollHideDelay);return()=>window.clearTimeout(d)}},[l,o.scrollHideDelay,u]),f.useEffect(()=>{const d=o.viewport,h=i?"scrollLeft":"scrollTop";if(d){let m=d[h];const g=()=>{const y=d[h];m!==y&&(u("SCROLL"),s()),m=y};return d.addEventListener("scroll",g),()=>d.removeEventListener("scroll",g)}},[o.viewport,i,u,s]),f.createElement(bn,{present:n||l!=="hidden"},f.createElement(Bx,Y({"data-state":l==="hidden"?"hidden":"visible"},r,{ref:t,onPointerEnter:ue(e.onPointerEnter,()=>u("POINTER_ENTER")),onPointerLeave:ue(e.onPointerLeave,()=>u("POINTER_LEAVE"))})))}),C5=f.forwardRef((e,t)=>{const n=qr($i,e.__scopeScrollArea),{forceMount:r,...o}=e,[i,s]=f.useState(!1),l=e.orientation==="horizontal",u=rg(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=e,o=qr($i,e.__scopeScrollArea),i=f.useRef(null),s=f.useRef(0),[l,u]=f.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=T5(l.viewport,l.content),h={...r,sizes:l,onSizesChange:u,hasThumb:d>0&&d<1,onThumbChange:g=>i.current=g,onThumbPointerUp:()=>s.current=0,onThumbPointerDown:g=>s.current=g};function m(g,y){return EG(g,s.current,l,y)}return n==="horizontal"?f.createElement(vG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollLeft,y=g2(g,l,o.dir);i.current.style.transform=`translate3d(${y}px, 0, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollLeft=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollLeft=m(g,o.dir))}})):n==="vertical"?f.createElement(yG,Y({},h,{ref:t,onThumbPositionChange:()=>{if(o.viewport&&i.current){const g=o.viewport.scrollTop,y=g2(g,l);i.current.style.transform=`translate3d(0, ${y}px, 0)`}},onWheelScroll:g=>{o.viewport&&(o.viewport.scrollTop=g)},onDragScroll:g=>{o.viewport&&(o.viewport.scrollTop=m(g))}})):null}),vG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarXChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"horizontal"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.x),onDragScroll:h=>e.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollLeft+h.deltaX;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:u.current.clientWidth,paddingStart:zh(s.paddingLeft),paddingEnd:zh(s.paddingRight)}})}}))}),yG=f.forwardRef((e,t)=>{const{sizes:n,onSizesChange:r,...o}=e,i=qr($i,e.__scopeScrollArea),[s,l]=f.useState(),u=f.useRef(null),d=Be(t,u,i.onScrollbarYChange);return f.useEffect(()=>{u.current&&l(getComputedStyle(u.current))},[u]),f.createElement(k5,Y({"data-orientation":"vertical"},o,{ref:d,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":ng(n)+"px",...e.style},onThumbPointerDown:h=>e.onThumbPointerDown(h.y),onDragScroll:h=>e.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(i.viewport){const g=i.viewport.scrollTop+h.deltaY;e.onWheelScroll(g),A5(g,m)&&h.preventDefault()}},onResize:()=>{u.current&&i.viewport&&s&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:u.current.clientHeight,paddingStart:zh(s.paddingTop),paddingEnd:zh(s.paddingBottom)}})}}))}),[wG,$5]=S5($i),k5=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:o,onThumbChange:i,onThumbPointerUp:s,onThumbPointerDown:l,onThumbPositionChange:u,onDragScroll:d,onWheelScroll:h,onResize:m,...g}=e,y=qr($i,n),[x,_]=f.useState(null),C=Be(t,F=>_(F)),S=f.useRef(null),b=f.useRef(""),E=y.viewport,k=r.content-r.viewport,P=Ft(h),M=Ft(u),A=rg(m,10);function O(F){if(S.current){const V=F.clientX-S.current.left,J=F.clientY-S.current.top;d({x:V,y:J})}}return f.useEffect(()=>{const F=V=>{const J=V.target;(x==null?void 0:x.contains(J))&&P(V,k)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[E,x,k,P]),f.useEffect(M,[r,M]),sc(x,A),sc(y.content,A),f.createElement(wG,{scope:n,scrollbar:x,hasThumb:o,onThumbChange:Ft(i),onThumbPointerUp:Ft(s),onThumbPositionChange:M,onThumbPointerDown:Ft(l)},f.createElement(Pe.div,Y({},g,{ref:C,style:{position:"absolute",...g.style},onPointerDown:ue(e.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),S.current=x.getBoundingClientRect(),b.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",y.viewport&&(y.viewport.style.scrollBehavior="auto"),O(F))}),onPointerMove:ue(e.onPointerMove,O),onPointerUp:ue(e.onPointerUp,F=>{const V=F.target;V.hasPointerCapture(F.pointerId)&&V.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=b.current,y.viewport&&(y.viewport.style.scrollBehavior=""),S.current=null})})))}),_1="ScrollAreaThumb",xG=f.forwardRef((e,t)=>{const{forceMount:n,...r}=e,o=$5(_1,e.__scopeScrollArea);return f.createElement(bn,{present:n||o.hasThumb},f.createElement(bG,Y({ref:t},r)))}),bG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,style:r,...o}=e,i=qr(_1,n),s=$5(_1,n),{onThumbPositionChange:l}=s,u=Be(t,m=>s.onThumbChange(m)),d=f.useRef(),h=rg(()=>{d.current&&(d.current(),d.current=void 0)},100);return f.useEffect(()=>{const m=i.viewport;if(m){const g=()=>{if(h(),!d.current){const y=CG(m,l);d.current=y,l()}};return l(),m.addEventListener("scroll",g),()=>m.removeEventListener("scroll",g)}},[i.viewport,h,l]),f.createElement(Pe.div,Y({"data-state":s.hasThumb?"visible":"hidden"},o,{ref:u,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:ue(e.onPointerDownCapture,m=>{const y=m.target.getBoundingClientRect(),x=m.clientX-y.left,_=m.clientY-y.top;s.onThumbPointerDown({x,y:_})}),onPointerUp:ue(e.onPointerUp,s.onThumbPointerUp)}))}),R5="ScrollAreaCorner",_G=f.forwardRef((e,t)=>{const n=qr(R5,e.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?f.createElement(SG,Y({},e,{ref:t})):null}),SG=f.forwardRef((e,t)=>{const{__scopeScrollArea:n,...r}=e,o=qr(R5,n),[i,s]=f.useState(0),[l,u]=f.useState(0),d=!!(i&&l);return sc(o.scrollbarX,()=>{var h;const m=((h=o.scrollbarX)===null||h===void 0?void 0:h.offsetHeight)||0;o.onCornerHeightChange(m),u(m)}),sc(o.scrollbarY,()=>{var h;const m=((h=o.scrollbarY)===null||h===void 0?void 0:h.offsetWidth)||0;o.onCornerWidthChange(m),s(m)}),d?f.createElement(Pe.div,Y({},r,{ref:t,style:{width:i,height:l,position:"absolute",right:o.dir==="ltr"?0:void 0,left:o.dir==="rtl"?0:void 0,bottom:0,...e.style}})):null});function zh(e){return e?parseInt(e,10):0}function T5(e,t){const n=e/t;return isNaN(n)?0:n}function ng(e){const t=T5(e.viewport,e.content),n=e.scrollbar.paddingStart+e.scrollbar.paddingEnd,r=(e.scrollbar.size-n)*t;return Math.max(r,18)}function EG(e,t,n,r="ltr"){const o=ng(n),i=o/2,s=t||i,l=o-s,u=n.scrollbar.paddingStart+s,d=n.scrollbar.size-n.scrollbar.paddingEnd-l,h=n.content-n.viewport,m=r==="ltr"?[0,h]:[h*-1,0];return P5([u,d],m)(e)}function g2(e,t,n="ltr"){const r=ng(t),o=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-o,s=t.content-t.viewport,l=i-r,u=n==="ltr"?[0,s]:[s*-1,0],d=id(e,u);return P5([0,s],[0,l])(d)}function P5(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function A5(e,t){return e>0&&e{})=>{let n={left:e.scrollLeft,top:e.scrollTop},r=0;return function o(){const i={left:e.scrollLeft,top:e.scrollTop},s=n.left!==i.left,l=n.top!==i.top;(s||l)&&t(),n=i,r=window.requestAnimationFrame(o)}(),()=>window.cancelAnimationFrame(r)};function rg(e,t){const n=Ft(e),r=f.useRef(0);return f.useEffect(()=>()=>window.clearTimeout(r.current),[]),f.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function sc(e,t){const n=Ft(t);Pn(()=>{let r=0;if(e){const o=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return o.observe(e),()=>{window.cancelAnimationFrame(r),o.unobserve(e)}}},[e,n])}const O5=fG,$G=hG,kG=_G,og=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(O5,{ref:r,className:Ce("relative overflow-hidden",e),scrollHideDelay:400,...n,children:[v.jsx($G,{className:"h-full w-full rounded-[inherit]",children:t}),v.jsx(M5,{}),v.jsx(kG,{})]}));og.displayName=O5.displayName;const M5=f.forwardRef(({className:e,orientation:t="vertical",...n},r)=>v.jsx(E5,{ref:r,orientation:t,className:Ce("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",e),...n,children:v.jsx(xG,{className:"relative flex-1 rounded-full bg-border"})}));M5.displayName=E5.displayName;const N5="Name",D5="Created time",I5="Modified time",v2="input",RG="output",y2={[xs.NAME]:N5,[xs.CTIME]:D5,[xs.MTIME]:I5};function TG(e){const{onPhotoClick:t,photoWidth:n}=e,[r,o]=AP(!1),[i,s]=bt(V=>[V.fileManagerState,V.updateFileManagerState]),{toast:l}=Td(),[u,d]=f.useState(0),[h,m]=f.useState(0),g=f.useRef(null),y=aV(i.searchText,300),[x,_]=f.useState(v2),[C,S]=f.useState([]),[b,E]=f.useState([]),[k,P]=f.useState(0);Zn("f",()=>{o()}),Zn("left",()=>{let V=k;k>0&&(V=k-1),P(V),t(x,b[V].name)},[k,b]),Zn("right",()=>{let V=k;k{r||m(u)},[r,u]);const M=f.useCallback(V=>{V!==null&&r&&setTimeout(()=>{V.scrollTo({top:h,left:0})},100)},[r,h]);f.useEffect(()=>{(async()=>{try{const J=await Vj(x);S(J)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[x]),f.useEffect(()=>{if(!r)return;(async()=>{try{let J=C;y&&(J=new _c(J,{keys:["name"]}).search(y).map(te=>J[te.refIndex])),J=wH.orderBy(J,i.sortBy,i.sortOrder);const G=J.map(ae=>{const U=n,te=ae.height*(U/ae.width);return{src:`${Ms}/media_thumbnail_file?tab=${x}&filename=${encodeURIComponent(ae.name)}&width=${Math.ceil(U)}&height=${Math.ceil(te)}`,height:te,width:U,name:ae.name}});E(G)}catch(J){l({variant:"destructive",title:"Uh oh! Something went wrong.",description:J.message?J.message:J.toString()})}})()},[C,y,i,n,r]);const A=V=>{d(V.currentTarget.scrollTop)},O=({index:V})=>{o(),P(V),t(x,b[V].name)},F=()=>v.jsxs("div",{className:"flex justify-start items-center gap-[12px]",children:[v.jsx("div",{children:`Images (${b.length})`}),v.jsxs("div",{className:"flex",children:[v.jsx(vn,{tooltip:"Rows layout",onClick:()=>{s({layout:"rows"})},children:v.jsx(pz,{className:i.layout!=="rows"?"opacity-50":""})}),v.jsx(vn,{tooltip:"Grid layout",onClick:()=>{s({layout:"masonry"})},children:v.jsx(dz,{className:i.layout!=="masonry"?"opacity-50":""})})]})]});return v.jsxs(Zm,{open:r,onOpenChange:o,children:[v.jsx(uP,{asChild:!0,children:v.jsx(vn,{tooltip:"File Manager",children:v.jsx(JU,{})})}),v.jsxs(Fd,{className:"h-4/5 max-w-6xl",children:[v.jsx(jd,{children:F()}),v.jsxs("div",{className:"flex justify-between gap-8 items-center",children:[v.jsxs("div",{className:"flex relative justify-start items-center",children:[v.jsx(az,{className:"absolute left-[8px]"}),v.jsx(Pd,{ref:g,value:i.searchText,className:"w-[250px] pl-[30px]",tabIndex:-1,onInput:V=>{V.preventDefault(),V.stopPropagation();const J=V.target;s({searchText:J.value})},placeholder:"Search by file name"})]}),v.jsx(i5,{defaultValue:x,onValueChange:V=>_(V),children:v.jsxs(Lx,{"aria-label":"Manage your account",children:[v.jsx(sa,{value:v2,children:"Image Directory"}),v.jsx(sa,{value:RG,children:"Output Directory"})]})}),v.jsx("div",{className:"flex gap-2",children:v.jsxs("div",{className:"flex gap-1",children:[v.jsxs(aa,{value:y2[i.sortBy],onValueChange:V=>{switch(V){case N5:s({sortBy:xs.NAME});break;case D5:s({sortBy:xs.CTIME});break;case I5:s({sortBy:xs.MTIME});break}},children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{})}),v.jsx(cs,{children:Object.values(y2).map(V=>v.jsx(us,{value:V,children:V},V))})]}),i.sortOrder===$u.DESCENDING?v.jsx(vn,{tooltip:"Descending Order",onClick:()=>{s({sortOrder:$u.ASCENDING})},children:v.jsx(oK,{})}):v.jsx(vn,{tooltip:"Ascending Order",onClick:()=>{s({sortOrder:$u.DESCENDING})},children:v.jsx(aK,{})})]})})]}),v.jsx(og,{className:"w-full h-full rounded-md",onScroll:A,ref:M,children:v.jsx(tK,{layout:i.layout,photos:b,spacing:12,padding:0,onClick:O})})]})]})}var Bd=e=>e.type==="checkbox",xl=e=>e instanceof Date,Ln=e=>e==null;const L5=e=>typeof e=="object";var sn=e=>!Ln(e)&&!Array.isArray(e)&&L5(e)&&!xl(e),F5=e=>sn(e)&&e.target?Bd(e.target)?e.target.checked:e.target.value:e,PG=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,j5=(e,t)=>e.has(PG(t)),AG=e=>{const t=e.constructor&&e.constructor.prototype;return sn(t)&&t.hasOwnProperty("isPrototypeOf")},Ux=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function so(e){let t;const n=Array.isArray(e);if(e instanceof Date)t=new Date(e);else if(e instanceof Set)t=new Set(e);else if(!(Ux&&(e instanceof Blob||e instanceof FileList))&&(n||sn(e)))if(t=n?[]:{},!n&&!AG(e))t=e;else for(const r in e)e.hasOwnProperty(r)&&(t[r]=so(e[r]));else return e;return t}var Ud=e=>Array.isArray(e)?e.filter(Boolean):[],Ht=e=>e===void 0,ve=(e,t,n)=>{if(!t||!sn(e))return n;const r=Ud(t.split(/[,[\].]+?/)).reduce((o,i)=>Ln(o)?o:o[i],e);return Ht(r)||r===e?Ht(e[t])?n:e[t]:r},No=e=>typeof e=="boolean";const Bh={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},mo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},oi={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},z5=Fe.createContext(null),ig=()=>Fe.useContext(z5),OG=e=>{const{children:t,...n}=e;return Fe.createElement(z5.Provider,{value:n},t)};var B5=(e,t,n,r=!0)=>{const o={defaultValues:t._defaultValues};for(const i in e)Object.defineProperty(o,i,{get:()=>{const s=i;return t._proxyFormState[s]!==mo.all&&(t._proxyFormState[s]=!r||mo.all),n&&(n[s]=!0),e[s]}});return o},Fr=e=>sn(e)&&!Object.keys(e).length,U5=(e,t,n,r)=>{n(e);const{name:o,...i}=e;return Fr(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(s=>t[s]===(!r||mo.all))},Yp=e=>Array.isArray(e)?e:[e],V5=(e,t,n)=>!e||!t||e===t||Yp(e).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r)));function Vx(e){const t=Fe.useRef(e);t.current=e,Fe.useEffect(()=>{const n=!e.disabled&&t.current.subject&&t.current.subject.subscribe({next:t.current.next});return()=>{n&&n.unsubscribe()}},[e.disabled])}function MG(e){const t=ig(),{control:n=t.control,disabled:r,name:o,exact:i}=e||{},[s,l]=Fe.useState(n._formState),u=Fe.useRef(!0),d=Fe.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1}),h=Fe.useRef(o);return h.current=o,Vx({disabled:r,next:m=>u.current&&V5(h.current,m.name,i)&&U5(m,d.current,n._updateFormState)&&l({...n._formState,...m}),subject:n._subjects.state}),Fe.useEffect(()=>(u.current=!0,d.current.isValid&&n._updateValid(!0),()=>{u.current=!1}),[n]),B5(s,n,d.current,!1)}var Fo=e=>typeof e=="string",W5=(e,t,n,r,o)=>Fo(e)?(r&&t.watch.add(e),ve(n,e,o)):Array.isArray(e)?e.map(i=>(r&&t.watch.add(i),ve(n,i))):(r&&(t.watchAll=!0),n);function NG(e){const t=ig(),{control:n=t.control,name:r,defaultValue:o,disabled:i,exact:s}=e||{},l=Fe.useRef(r);l.current=r,Vx({disabled:i,subject:n._subjects.values,next:h=>{V5(l.current,h.name,s)&&d(so(W5(l.current,n._names,h.values||n._formValues,!1,o)))}});const[u,d]=Fe.useState(n._getWatch(r,o));return Fe.useEffect(()=>n._removeUnmounted()),u}var Wx=e=>/^\w*$/.test(e),H5=e=>Ud(e.replace(/["|']|\]/g,"").split(/\.|\[/));function wt(e,t,n){let r=-1;const o=Wx(t)?[t]:H5(t),i=o.length,s=i-1;for(;++r{const h=o._options.shouldUnregister||i,m=(g,y)=>{const x=ve(o._fields,g);x&&(x._f.mount=y)};if(m(n,!0),h){const g=so(ve(o._options.defaultValues,n));wt(o._defaultValues,n,g),Ht(ve(o._formValues,n))&&wt(o._formValues,n,g)}return()=>{(s?h&&!o._state.action:h)?o.unregister(n):m(n,!1)}},[n,o,s,i]),Fe.useEffect(()=>{ve(o._fields,n)&&o._updateDisabledField({disabled:r,fields:o._fields,name:n,value:ve(o._fields,n)._f.value})},[r,n,o]),{field:{name:n,value:l,...No(r)||No(u.disabled)?{disabled:u.disabled||r}:{},onChange:Fe.useCallback(h=>d.current.onChange({target:{value:F5(h),name:n},type:Bh.CHANGE}),[n]),onBlur:Fe.useCallback(()=>d.current.onBlur({target:{value:ve(o._formValues,n),name:n},type:Bh.BLUR}),[n,o]),ref:h=>{const m=ve(o._fields,n);m&&h&&(m._f.ref={focus:()=>h.focus(),select:()=>h.select(),setCustomValidity:g=>h.setCustomValidity(g),reportValidity:()=>h.reportValidity()})}},formState:u,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ve(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!ve(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!ve(u.touchedFields,n)},error:{enumerable:!0,get:()=>ve(u.errors,n)}})}}const IG=e=>e.render(DG(e));var K5=(e,t,n,r,o)=>t?{...n[e],types:{...n[e]&&n[e].types?n[e].types:{},[r]:o||!0}}:{},w2=e=>({isOnSubmit:!e||e===mo.onSubmit,isOnBlur:e===mo.onBlur,isOnChange:e===mo.onChange,isOnAll:e===mo.all,isOnTouch:e===mo.onTouched}),x2=(e,t,n)=>!n&&(t.watchAll||t.watch.has(e)||[...t.watch].some(r=>e.startsWith(r)&&/^\.\w+/.test(e.slice(r.length))));const Gp=(e,t,n,r)=>{for(const o of n||Object.keys(e)){const i=ve(e,o);if(i){const{_f:s,...l}=i;if(s){if(s.refs&&s.refs[0]&&t(s.refs[0],o)&&!r)break;if(s.ref&&t(s.ref,s.name)&&!r)break}else sn(l)&&Gp(l,t)}}};var LG=(e,t,n)=>{const r=Ud(ve(e,n));return wt(r,"root",t[n]),wt(e,n,r),e},Hx=e=>e.type==="file",ds=e=>typeof e=="function",Uh=e=>{if(!Ux)return!1;const t=e?e.ownerDocument:0;return e instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Xp=e=>Fo(e),Kx=e=>e.type==="radio",Vh=e=>e instanceof RegExp;const b2={value:!1,isValid:!1},_2={value:!0,isValid:!0};var Y5=e=>{if(Array.isArray(e)){if(e.length>1){const t=e.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!Ht(e[0].attributes.value)?Ht(e[0].value)||e[0].value===""?_2:{value:e[0].value,isValid:!0}:_2:b2}return b2};const S2={isValid:!1,value:null};var G5=e=>Array.isArray(e)?e.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,S2):S2;function E2(e,t,n="validate"){if(Xp(e)||Array.isArray(e)&&e.every(Xp)||No(e)&&!e)return{type:n,message:Xp(e)?e:"",ref:t}}var el=e=>sn(e)&&!Vh(e)?e:{value:e,message:""},C2=async(e,t,n,r,o)=>{const{ref:i,refs:s,required:l,maxLength:u,minLength:d,min:h,max:m,pattern:g,validate:y,name:x,valueAsNumber:_,mount:C,disabled:S}=e._f,b=ve(t,x);if(!C||S)return{};const E=s?s[0]:i,k=G=>{r&&E.reportValidity&&(E.setCustomValidity(No(G)?"":G||""),E.reportValidity())},P={},M=Kx(i),A=Bd(i),O=M||A,F=(_||Hx(i))&&Ht(i.value)&&Ht(b)||Uh(i)&&i.value===""||b===""||Array.isArray(b)&&!b.length,V=K5.bind(null,x,n,P),J=(G,ae,U,te=oi.maxLength,L=oi.minLength)=>{const ie=G?ae:U;P[x]={type:G?te:L,message:ie,ref:i,...V(G?te:L,ie)}};if(o?!Array.isArray(b)||!b.length:l&&(!O&&(F||Ln(b))||No(b)&&!b||A&&!Y5(s).isValid||M&&!G5(s).isValid)){const{value:G,message:ae}=Xp(l)?{value:!!l,message:l}:el(l);if(G&&(P[x]={type:oi.required,message:ae,ref:E,...V(oi.required,ae)},!n))return k(ae),P}if(!F&&(!Ln(h)||!Ln(m))){let G,ae;const U=el(m),te=el(h);if(!Ln(b)&&!isNaN(b)){const L=i.valueAsNumber||b&&+b;Ln(U.value)||(G=L>U.value),Ln(te.value)||(ae=Lnew Date(new Date().toDateString()+" "+W),K=i.type=="time",Q=i.type=="week";Fo(U.value)&&b&&(G=K?ie(b)>ie(U.value):Q?b>U.value:L>new Date(U.value)),Fo(te.value)&&b&&(ae=K?ie(b)+G.value,te=!Ln(ae.value)&&b.length<+ae.value;if((U||te)&&(J(U,G.message,ae.message),!n))return k(P[x].message),P}if(g&&!F&&Fo(b)){const{value:G,message:ae}=el(g);if(Vh(G)&&!b.match(G)&&(P[x]={type:oi.pattern,message:ae,ref:i,...V(oi.pattern,ae)},!n))return k(ae),P}if(y){if(ds(y)){const G=await y(b,t),ae=E2(G,E);if(ae&&(P[x]={...ae,...V(oi.validate,ae.message)},!n))return k(ae.message),P}else if(sn(y)){let G={};for(const ae in y){if(!Fr(G)&&!n)break;const U=E2(await y[ae](b,t),E,ae);U&&(G={...U,...V(ae,U.message)},k(U.message),n&&(P[x]=G))}if(!Fr(G)&&(P[x]={ref:E,...G},!n))return P}}return k(!0),P};function FG(e,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const i of e)i.next&&i.next(o)},subscribe:o=>(e.push(o),{unsubscribe:()=>{e=e.filter(i=>i!==o)}}),unsubscribe:()=>{e=[]}}}var Wh=e=>Ln(e)||!L5(e);function ca(e,t){if(Wh(e)||Wh(t))return e===t;if(xl(e)&&xl(t))return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const o of n){const i=e[o];if(!r.includes(o))return!1;if(o!=="ref"){const s=t[o];if(xl(i)&&xl(s)||sn(i)&&sn(s)||Array.isArray(i)&&Array.isArray(s)?!ca(i,s):i!==s)return!1}}return!0}var X5=e=>e.type==="select-multiple",zG=e=>Kx(e)||Bd(e),P0=e=>Uh(e)&&e.isConnected,Z5=e=>{for(const t in e)if(ds(e[t]))return!0;return!1};function Hh(e,t={}){const n=Array.isArray(e);if(sn(e)||n)for(const r in e)Array.isArray(e[r])||sn(e[r])&&!Z5(e[r])?(t[r]=Array.isArray(e[r])?[]:{},Hh(e[r],t[r])):Ln(e[r])||(t[r]=!0);return t}function q5(e,t,n){const r=Array.isArray(e);if(sn(e)||r)for(const o in e)Array.isArray(e[o])||sn(e[o])&&!Z5(e[o])?Ht(t)||Wh(n[o])?n[o]=Array.isArray(e[o])?Hh(e[o],[]):{...Hh(e[o])}:q5(e[o],Ln(t)?{}:t[o],n[o]):n[o]=!ca(e[o],t[o]);return n}var A0=(e,t)=>q5(e,t,Hh(t)),Q5=(e,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>Ht(e)?e:t?e===""?NaN:e&&+e:n&&Fo(e)?new Date(e):r?r(e):e;function O0(e){const t=e.ref;if(!(e.refs?e.refs.every(n=>n.disabled):t.disabled))return Hx(t)?t.files:Kx(t)?G5(e.refs).value:X5(t)?[...t.selectedOptions].map(({value:n})=>n):Bd(t)?Y5(e.refs).value:Q5(Ht(t.value)?e.ref.value:t.value,e)}var BG=(e,t,n,r)=>{const o={};for(const i of e){const s=ve(t,i);s&&wt(o,i,s._f)}return{criteriaMode:n,names:[...e],fields:o,shouldUseNativeValidation:r}},iu=e=>Ht(e)?e:Vh(e)?e.source:sn(e)?Vh(e.value)?e.value.source:e.value:e,UG=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function $2(e,t,n){const r=ve(e,n);if(r||Wx(n))return{error:r,name:n};const o=n.split(".");for(;o.length;){const i=o.join("."),s=ve(t,i),l=ve(e,i);if(s&&!Array.isArray(s)&&n!==i)return{name:n};if(l&&l.type)return{name:i,error:l};o.pop()}return{name:n}}var VG=(e,t,n,r,o)=>o.isOnAll?!1:!n&&o.isOnTouch?!(t||e):(n?r.isOnBlur:o.isOnBlur)?!e:(n?r.isOnChange:o.isOnChange)?e:!0,WG=(e,t)=>!Ud(ve(e,t)).length&&hn(e,t);const HG={mode:mo.onSubmit,reValidateMode:mo.onChange,shouldFocusError:!0};function KG(e={},t){let n={...HG,...e},r={submitCount:0,isDirty:!1,isLoading:ds(n.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{},disabled:!1},o={},i=sn(n.defaultValues)||sn(n.values)?so(n.defaultValues||n.values)||{}:{},s=n.shouldUnregister?{}:so(i),l={action:!1,mount:!1,watch:!1},u={mount:new Set,unMount:new Set,array:new Set,watch:new Set},d,h=0;const m={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={values:T0(),array:T0(),state:T0()},y=e.resetOptions&&e.resetOptions.keepDirtyValues,x=w2(n.mode),_=w2(n.reValidateMode),C=n.criteriaMode===mo.all,S=I=>X=>{clearTimeout(h),h=setTimeout(I,X)},b=async I=>{if(m.isValid||I){const X=n.resolver?Fr((await F()).errors):await J(o,!0);X!==r.isValid&&g.state.next({isValid:X})}},E=I=>m.isValidating&&g.state.next({isValidating:I}),k=(I,X=[],Z,we,he=!0,de=!0)=>{if(we&&Z){if(l.action=!0,de&&Array.isArray(ve(o,I))){const ke=Z(ve(o,I),we.argA,we.argB);he&&wt(o,I,ke)}if(de&&Array.isArray(ve(r.errors,I))){const ke=Z(ve(r.errors,I),we.argA,we.argB);he&&wt(r.errors,I,ke),WG(r.errors,I)}if(m.touchedFields&&de&&Array.isArray(ve(r.touchedFields,I))){const ke=Z(ve(r.touchedFields,I),we.argA,we.argB);he&&wt(r.touchedFields,I,ke)}m.dirtyFields&&(r.dirtyFields=A0(i,s)),g.state.next({name:I,isDirty:ae(I,X),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else wt(s,I,X)},P=(I,X)=>{wt(r.errors,I,X),g.state.next({errors:r.errors})},M=(I,X,Z,we)=>{const he=ve(o,I);if(he){const de=ve(s,I,Ht(Z)?ve(i,I):Z);Ht(de)||we&&we.defaultChecked||X?wt(s,I,X?de:O0(he._f)):L(I,de),l.mount&&b()}},A=(I,X,Z,we,he)=>{let de=!1,ke=!1;const ft={name:I};if(!Z||we){m.isDirty&&(ke=r.isDirty,r.isDirty=ft.isDirty=ae(),de=ke!==ft.isDirty);const pt=ca(ve(i,I),X);ke=ve(r.dirtyFields,I),pt?hn(r.dirtyFields,I):wt(r.dirtyFields,I,!0),ft.dirtyFields=r.dirtyFields,de=de||m.dirtyFields&&ke!==!pt}if(Z){const pt=ve(r.touchedFields,I);pt||(wt(r.touchedFields,I,Z),ft.touchedFields=r.touchedFields,de=de||m.touchedFields&&pt!==Z)}return de&&he&&g.state.next(ft),de?ft:{}},O=(I,X,Z,we)=>{const he=ve(r.errors,I),de=m.isValid&&No(X)&&r.isValid!==X;if(e.delayError&&Z?(d=S(()=>P(I,Z)),d(e.delayError)):(clearTimeout(h),d=null,Z?wt(r.errors,I,Z):hn(r.errors,I)),(Z?!ca(he,Z):he)||!Fr(we)||de){const ke={...we,...de&&No(X)?{isValid:X}:{},errors:r.errors,name:I};r={...r,...ke},g.state.next(ke)}E(!1)},F=async I=>n.resolver(s,n.context,BG(I||u.mount,o,n.criteriaMode,n.shouldUseNativeValidation)),V=async I=>{const{errors:X}=await F(I);if(I)for(const Z of I){const we=ve(X,Z);we?wt(r.errors,Z,we):hn(r.errors,Z)}else r.errors=X;return X},J=async(I,X,Z={valid:!0})=>{for(const we in I){const he=I[we];if(he){const{_f:de,...ke}=he;if(de){const ft=u.array.has(de.name),pt=await C2(he,s,C,n.shouldUseNativeValidation&&!X,ft);if(pt[de.name]&&(Z.valid=!1,X))break;!X&&(ve(pt,de.name)?ft?LG(r.errors,pt,de.name):wt(r.errors,de.name,pt[de.name]):hn(r.errors,de.name))}ke&&await J(ke,X,Z)}}return Z.valid},G=()=>{for(const I of u.unMount){const X=ve(o,I);X&&(X._f.refs?X._f.refs.every(Z=>!P0(Z)):!P0(X._f.ref))&&fe(I)}u.unMount=new Set},ae=(I,X)=>(I&&X&&wt(s,I,X),!ca(ge(),i)),U=(I,X,Z)=>W5(I,u,{...l.mount?s:Ht(X)?i:Fo(I)?{[I]:X}:X},Z,X),te=I=>Ud(ve(l.mount?s:i,I,e.shouldUnregister?ve(i,I,[]):[])),L=(I,X,Z={})=>{const we=ve(o,I);let he=X;if(we){const de=we._f;de&&(!de.disabled&&wt(s,I,Q5(X,de)),he=Uh(de.ref)&&Ln(X)?"":X,X5(de.ref)?[...de.ref.options].forEach(ke=>ke.selected=he.includes(ke.value)):de.refs?Bd(de.ref)?de.refs.length>1?de.refs.forEach(ke=>(!ke.defaultChecked||!ke.disabled)&&(ke.checked=Array.isArray(he)?!!he.find(ft=>ft===ke.value):he===ke.value)):de.refs[0]&&(de.refs[0].checked=!!he):de.refs.forEach(ke=>ke.checked=ke.value===he):Hx(de.ref)?de.ref.value="":(de.ref.value=he,de.ref.type||g.values.next({name:I,values:{...s}})))}(Z.shouldDirty||Z.shouldTouch)&&A(I,he,Z.shouldTouch,Z.shouldDirty,!0),Z.shouldValidate&&le(I)},ie=(I,X,Z)=>{for(const we in X){const he=X[we],de=`${I}.${we}`,ke=ve(o,de);(u.array.has(I)||!Wh(he)||ke&&!ke._f)&&!xl(he)?ie(de,he,Z):L(de,he,Z)}},K=(I,X,Z={})=>{const we=ve(o,I),he=u.array.has(I),de=so(X);wt(s,I,de),he?(g.array.next({name:I,values:{...s}}),(m.isDirty||m.dirtyFields)&&Z.shouldDirty&&g.state.next({name:I,dirtyFields:A0(i,s),isDirty:ae(I,de)})):we&&!we._f&&!Ln(de)?ie(I,de,Z):L(I,de,Z),x2(I,u)&&g.state.next({...r}),g.values.next({name:I,values:{...s}}),!l.mount&&t()},Q=async I=>{const X=I.target;let Z=X.name,we=!0;const he=ve(o,Z),de=()=>X.type?O0(he._f):F5(I),ke=ft=>{we=Number.isNaN(ft)||ft===ve(s,Z,ft)};if(he){let ft,pt;const _n=de(),Cr=I.type===Bh.BLUR||I.type===Bh.FOCUS_OUT,ki=!UG(he._f)&&!n.resolver&&!ve(r.errors,Z)&&!he._f.deps||VG(Cr,ve(r.touchedFields,Z),r.isSubmitted,_,x),_o=x2(Z,u,Cr);wt(s,Z,_n),Cr?(he._f.onBlur&&he._f.onBlur(I),d&&d(0)):he._f.onChange&&he._f.onChange(I);const Vn=A(Z,_n,Cr,!1),Da=!Fr(Vn)||_o;if(!Cr&&g.values.next({name:Z,type:I.type,values:{...s}}),ki)return m.isValid&&b(),Da&&g.state.next({name:Z,..._o?{}:Vn});if(!Cr&&_o&&g.state.next({...r}),E(!0),n.resolver){const{errors:Ri}=await F([Z]);if(ke(_n),we){const zs=$2(r.errors,o,Z),Ti=$2(Ri,o,zs.name||Z);ft=Ti.error,Z=Ti.name,pt=Fr(Ri)}}else ft=(await C2(he,s,C,n.shouldUseNativeValidation))[Z],ke(_n),we&&(ft?pt=!1:m.isValid&&(pt=await J(o,!0)));we&&(he._f.deps&&le(he._f.deps),O(Z,pt,ft,Vn))}},W=(I,X)=>{if(ve(r.errors,X)&&I.focus)return I.focus(),1},le=async(I,X={})=>{let Z,we;const he=Yp(I);if(E(!0),n.resolver){const de=await V(Ht(I)?I:he);Z=Fr(de),we=I?!he.some(ke=>ve(de,ke)):Z}else I?(we=(await Promise.all(he.map(async de=>{const ke=ve(o,de);return await J(ke&&ke._f?{[de]:ke}:ke)}))).every(Boolean),!(!we&&!r.isValid)&&b()):we=Z=await J(o);return g.state.next({...!Fo(I)||m.isValid&&Z!==r.isValid?{}:{name:I},...n.resolver||!I?{isValid:Z}:{},errors:r.errors,isValidating:!1}),X.shouldFocus&&!we&&Gp(o,W,I?he:u.mount),we},ge=I=>{const X={...i,...l.mount?s:{}};return Ht(I)?X:Fo(I)?ve(X,I):I.map(Z=>ve(X,Z))},Ve=(I,X)=>({invalid:!!ve((X||r).errors,I),isDirty:!!ve((X||r).dirtyFields,I),isTouched:!!ve((X||r).touchedFields,I),error:ve((X||r).errors,I)}),Ue=I=>{I&&Yp(I).forEach(X=>hn(r.errors,X)),g.state.next({errors:I?r.errors:{}})},We=(I,X,Z)=>{const we=(ve(o,I,{_f:{}})._f||{}).ref;wt(r.errors,I,{...X,ref:we}),g.state.next({name:I,errors:r.errors,isValid:!1}),Z&&Z.shouldFocus&&we&&we.focus&&we.focus()},Me=(I,X)=>ds(I)?g.values.subscribe({next:Z=>I(U(void 0,X),Z)}):U(I,X,!0),fe=(I,X={})=>{for(const Z of I?Yp(I):u.mount)u.mount.delete(Z),u.array.delete(Z),X.keepValue||(hn(o,Z),hn(s,Z)),!X.keepError&&hn(r.errors,Z),!X.keepDirty&&hn(r.dirtyFields,Z),!X.keepTouched&&hn(r.touchedFields,Z),!n.shouldUnregister&&!X.keepDefaultValue&&hn(i,Z);g.values.next({values:{...s}}),g.state.next({...r,...X.keepDirty?{isDirty:ae()}:{}}),!X.keepIsValid&&b()},xe=({disabled:I,name:X,field:Z,fields:we,value:he})=>{if(No(I)){const de=I?void 0:Ht(he)?O0(Z?Z._f:ve(we,X)._f):he;wt(s,X,de),A(X,de,!1,!1,!0)}},$e=(I,X={})=>{let Z=ve(o,I);const we=No(X.disabled);return wt(o,I,{...Z||{},_f:{...Z&&Z._f?Z._f:{ref:{name:I}},name:I,mount:!0,...X}}),u.mount.add(I),Z?xe({field:Z,disabled:X.disabled,name:I}):M(I,!0,X.value),{...we?{disabled:X.disabled}:{},...n.progressive?{required:!!X.required,min:iu(X.min),max:iu(X.max),minLength:iu(X.minLength),maxLength:iu(X.maxLength),pattern:iu(X.pattern)}:{},name:I,onChange:Q,onBlur:Q,ref:he=>{if(he){$e(I,X),Z=ve(o,I);const de=Ht(he.value)&&he.querySelectorAll&&he.querySelectorAll("input,select,textarea")[0]||he,ke=zG(de),ft=Z._f.refs||[];if(ke?ft.find(pt=>pt===de):de===Z._f.ref)return;wt(o,I,{_f:{...Z._f,...ke?{refs:[...ft.filter(P0),de,...Array.isArray(ve(i,I))?[{}]:[]],ref:{type:de.type,name:I}}:{ref:de}}}),M(I,!1,void 0,de)}else Z=ve(o,I,{}),Z._f&&(Z._f.mount=!1),(n.shouldUnregister||X.shouldUnregister)&&!(j5(u.array,I)&&l.action)&&u.unMount.add(I)}}},Ae=()=>n.shouldFocusError&&Gp(o,W,u.mount),Oe=I=>{No(I)&&(g.state.next({disabled:I}),Gp(o,X=>{X.disabled=I},0,!1))},je=(I,X)=>async Z=>{Z&&(Z.preventDefault&&Z.preventDefault(),Z.persist&&Z.persist());let we=so(s);if(g.state.next({isSubmitting:!0}),n.resolver){const{errors:he,values:de}=await F();r.errors=he,we=de}else await J(o);hn(r.errors,"root"),Fr(r.errors)?(g.state.next({errors:{}}),await I(we,Z)):(X&&await X({...r.errors},Z),Ae(),setTimeout(Ae)),g.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Fr(r.errors),submitCount:r.submitCount+1,errors:r.errors})},Ot=(I,X={})=>{ve(o,I)&&(Ht(X.defaultValue)?K(I,ve(i,I)):(K(I,X.defaultValue),wt(i,I,X.defaultValue)),X.keepTouched||hn(r.touchedFields,I),X.keepDirty||(hn(r.dirtyFields,I),r.isDirty=X.defaultValue?ae(I,ve(i,I)):ae()),X.keepError||(hn(r.errors,I),m.isValid&&b()),g.state.next({...r}))},ct=(I,X={})=>{const Z=I?so(I):i,we=so(Z),he=I&&!Fr(I)?we:i;if(X.keepDefaultValues||(i=Z),!X.keepValues){if(X.keepDirtyValues||y)for(const de of u.mount)ve(r.dirtyFields,de)?wt(he,de,ve(s,de)):K(de,ve(he,de));else{if(Ux&&Ht(I))for(const de of u.mount){const ke=ve(o,de);if(ke&&ke._f){const ft=Array.isArray(ke._f.refs)?ke._f.refs[0]:ke._f.ref;if(Uh(ft)){const pt=ft.closest("form");if(pt){pt.reset();break}}}}o={}}s=e.shouldUnregister?X.keepDefaultValues?so(i):{}:so(he),g.array.next({values:{...he}}),g.values.next({values:{...he}})}u={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},!l.mount&&t(),l.mount=!m.isValid||!!X.keepIsValid,l.watch=!!e.shouldUnregister,g.state.next({submitCount:X.keepSubmitCount?r.submitCount:0,isDirty:X.keepDirty?r.isDirty:!!(X.keepDefaultValues&&!ca(I,i)),isSubmitted:X.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:X.keepDirtyValues?r.dirtyFields:X.keepDefaultValues&&I?A0(i,I):{},touchedFields:X.keepTouched?r.touchedFields:{},errors:X.keepErrors?r.errors:{},isSubmitSuccessful:X.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},Kt=(I,X)=>ct(ds(I)?I(s):I,X);return{control:{register:$e,unregister:fe,getFieldState:Ve,handleSubmit:je,setError:We,_executeSchema:F,_getWatch:U,_getDirty:ae,_updateValid:b,_removeUnmounted:G,_updateFieldArray:k,_updateDisabledField:xe,_getFieldArray:te,_reset:ct,_resetDefaultValues:()=>ds(n.defaultValues)&&n.defaultValues().then(I=>{Kt(I,n.resetOptions),g.state.next({isLoading:!1})}),_updateFormState:I=>{r={...r,...I}},_disableForm:Oe,_subjects:g,_proxyFormState:m,get _fields(){return o},get _formValues(){return s},get _state(){return l},set _state(I){l=I},get _defaultValues(){return i},get _names(){return u},set _names(I){u=I},get _formState(){return r},set _formState(I){r=I},get _options(){return n},set _options(I){n={...n,...I}}},trigger:le,register:$e,handleSubmit:je,watch:Me,setValue:K,getValues:ge,reset:Kt,resetField:Ot,clearErrors:Ue,unregister:fe,setError:We,setFocus:(I,X={})=>{const Z=ve(o,I),we=Z&&Z._f;if(we){const he=we.refs?we.refs[0]:we.ref;he.focus&&(he.focus(),X.shouldSelect&&he.select())}},getFieldState:Ve}}function YG(e={}){const t=Fe.useRef(),n=Fe.useRef(),[r,o]=Fe.useState({isDirty:!1,isValidating:!1,isLoading:ds(e.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},disabled:!1,defaultValues:ds(e.defaultValues)?void 0:e.defaultValues});t.current||(t.current={...KG(e,()=>o(s=>({...s}))),formState:r});const i=t.current.control;return i._options=e,Vx({subject:i._subjects.state,next:s=>{U5(s,i._proxyFormState,i._updateFormState,!0)&&o({...i._formState})}}),Fe.useEffect(()=>i._disableForm(e.disabled),[i,e.disabled]),Fe.useEffect(()=>{if(i._proxyFormState.isDirty){const s=i._getDirty();s!==r.isDirty&&i._subjects.state.next({isDirty:s})}},[i,r.isDirty]),Fe.useEffect(()=>{e.values&&!ca(e.values,n.current)?(i._reset(e.values,i._options.resetOptions),n.current=e.values):i._resetDefaultValues()},[e.values,i]),Fe.useEffect(()=>{i._state.mount||(i._updateValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),t.current.formState=B5(r,i),t.current}var k2=function(e,t,n){if(e&&"reportValidity"in e){var r=ve(n,t);e.setCustomValidity(r&&r.message||""),e.reportValidity()}},J5=function(e,t){var n=function(o){var i=t.fields[o];i&&i.ref&&"reportValidity"in i.ref?k2(i.ref,o,e):i.refs&&i.refs.forEach(function(s){return k2(s,o,e)})};for(var r in t.fields)n(r)},GG=function(e,t){t.shouldUseNativeValidation&&J5(e,t);var n={};for(var r in e){var o=ve(t.fields,r),i=Object.assign(e[r]||{},{ref:o&&o.ref});if(ZG(t.names||Object.keys(e),r)){var s=Object.assign({},XG(ve(n,r)));wt(s,"root",i),wt(n,r,s)}else wt(n,r,i)}return n},XG=function(e){return Array.isArray(e)?e.filter(Boolean):[]},ZG=function(e,t){return e.some(function(n){return n.startsWith(t+".")})},qG=function(e,t){for(var n={};e.length;){var r=e[0],o=r.code,i=r.message,s=r.path.join(".");if(!n[s])if("unionErrors"in r){var l=r.unionErrors[0].errors[0];n[s]={message:l.message,type:l.code}}else n[s]={message:i,type:o};if("unionErrors"in r&&r.unionErrors.forEach(function(h){return h.errors.forEach(function(m){return e.push(m)})}),t){var u=n[s].types,d=u&&u[r.code];n[s]=K5(s,t,n,o,d?[].concat(d,r.message):r.message)}e.shift()}return n},QG=function(e,t,n){return n===void 0&&(n={}),function(r,o,i){try{return Promise.resolve(function(s,l){try{var u=Promise.resolve(e[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&J5({},i),{errors:{},values:n.raw?r:d}})}catch(d){return l(d)}return u&&u.then?u.then(void 0,l):u}(0,function(s){if(function(l){return l.errors!=null}(s))return{values:{},errors:GG(qG(s.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw s}))}catch(s){return Promise.reject(s)}}},mt;(function(e){e.assertEqual=o=>o;function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{const i={};for(const s of o)i[s]=s;return i},e.getValidEnumValues=o=>{const i=e.objectKeys(o).filter(l=>typeof o[o[l]]!="number"),s={};for(const l of i)s[l]=o[l];return e.objectValues(s)},e.objectValues=o=>e.objectKeys(o).map(function(i){return o[i]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{const i=[];for(const s in o)Object.prototype.hasOwnProperty.call(o,s)&&i.push(s);return i},e.find=(o,i)=>{for(const s of o)if(i(s))return s},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(s=>typeof s=="string"?`'${s}'`:s).join(i)}e.joinValues=r,e.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(mt||(mt={}));var R2;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(R2||(R2={}));const be=mt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ta=e=>{switch(typeof e){case"undefined":return be.undefined;case"string":return be.string;case"number":return isNaN(e)?be.nan:be.number;case"boolean":return be.boolean;case"function":return be.function;case"bigint":return be.bigint;case"symbol":return be.symbol;case"object":return Array.isArray(e)?be.array:e===null?be.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?be.promise:typeof Map<"u"&&e instanceof Map?be.map:typeof Set<"u"&&e instanceof Set?be.set:typeof Date<"u"&&e instanceof Date?be.date:be.object;default:return be.unknown}},pe=mt.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"]);class Bo extends Error{constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}get errors(){return this.issues}format(t){const n=t||function(i){return i.message},r={_errors:[]},o=i=>{for(const 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 l=r,u=0;for(;un.message){const n={},r=[];for(const o of this.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(t(o))):r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Bo.create=e=>new Bo(e);const Kh=(e,t)=>{let n;switch(e.code){case pe.invalid_type:e.received===be.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case pe.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,mt.jsonStringifyReplacer)}`;break;case pe.unrecognized_keys:n=`Unrecognized key(s) in object: ${mt.joinValues(e.keys,", ")}`;break;case pe.invalid_union:n="Invalid input";break;case pe.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${mt.joinValues(e.options)}`;break;case pe.invalid_enum_value:n=`Invalid enum value. Expected ${mt.joinValues(e.options)}, received '${e.received}'`;break;case pe.invalid_arguments:n="Invalid function arguments";break;case pe.invalid_return_type:n="Invalid function return type";break;case pe.invalid_date:n="Invalid date";break;case pe.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:mt.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case pe.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case pe.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case pe.custom:n="Invalid input";break;case pe.invalid_intersection_types:n="Intersection results could not be merged";break;case pe.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case pe.not_finite:n="Number must be finite";break;default:n=t.defaultError,mt.assertNever(e)}return{message:n}};let JG=Kh;function S1(){return JG}const E1=e=>{const{data:t,path:n,errorMaps:r,issueData:o}=e,i=[...n,...o.path||[]],s={...o,path:i};let l="";const u=r.filter(d=>!!d).slice().reverse();for(const d of u)l=d(s,{data:t,defaultError:l}).message;return{...o,path:i,message:o.message||l}};function Ee(e,t){const n=E1({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,S1(),Kh].filter(r=>!!r)});e.common.issues.push(n)}class zn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){const r=[];for(const o of n){if(o.status==="aborted")return Ze;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){const r=[];for(const o of n)r.push({key:await o.key,value:await o.value});return zn.mergeObjectSync(t,r)}static mergeObjectSync(t,n){const r={};for(const o of n){const{key:i,value:s}=o;if(i.status==="aborted"||s.status==="aborted")return Ze;i.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),i.value!=="__proto__"&&(typeof s.value<"u"||o.alwaysSet)&&(r[i.value]=s.value)}return{status:t.value,value:r}}}const Ze=Object.freeze({status:"aborted"}),eX=e=>({status:"dirty",value:e}),rr=e=>({status:"valid",value:e}),T2=e=>e.status==="aborted",P2=e=>e.status==="dirty",Yh=e=>e.status==="valid",C1=e=>typeof Promise<"u"&&e instanceof Promise;var Ne;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(Ne||(Ne={}));class Ko{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const A2=(e,t)=>{if(Yh(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Bo(e.common.issues);return this._error=n,this._error}}};function Xe(e){if(!e)return{};const{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(s,l)=>s.code!=="invalid_type"?{message:l.defaultError}:typeof l.data>"u"?{message:r??l.defaultError}:{message:n??l.defaultError},description:o}}class rt{constructor(t){this.spa=this.safeParseAsync,this._def=t,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)}get description(){return this._def.description}_getType(t){return ta(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new zn,ctx:{common:t.parent.common,data:t.data,parsedType:ta(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const n=this._parse(t);if(C1(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){const n=this._parse(t);return Promise.resolve(n)}parse(t,n){const r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){var r;const o={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},i=this._parseSync({data:t,path:o.path,parent:o});return A2(o,i)}async parseAsync(t,n){const r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:ta(t)},o=this._parse({data:t,path:r.path,parent:r}),i=await(C1(o)?o:Promise.resolve(o));return A2(r,i)}refine(t,n){const r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,i)=>{const s=t(o),l=()=>i.addIssue({code:pe.custom,...r(o)});return typeof Promise<"u"&&s instanceof Promise?s.then(u=>u?!0:(l(),!1)):s?!0:(l(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Si({schema:this,typeName:ze.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}optional(){return bs.create(this,this._def)}nullable(){return uc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Uo.create(this,this._def)}promise(){return ad.create(this,this._def)}or(t){return Zh.create([this,t],this._def)}and(t){return qh.create(this,t,this._def)}transform(t){return new Si({...Xe(this._def),schema:this,typeName:ze.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const n=typeof t=="function"?t:()=>t;return new nm({...Xe(this._def),innerType:this,defaultValue:n,typeName:ze.ZodDefault})}brand(){return new fX({typeName:ze.ZodBranded,type:this,...Xe(this._def)})}catch(t){const n=typeof t=="function"?t:()=>t;return new O1({...Xe(this._def),innerType:this,catchValue:n,typeName:ze.ZodCatch})}describe(t){const n=this.constructor;return new n({...this._def,description:t})}pipe(t){return sg.create(this,t)}readonly(){return N1.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const tX=/^c[^\s-]{8,}$/i,nX=/^[a-z][a-z0-9]*$/,rX=/^[0-9A-HJKMNP-TV-Z]{26}$/,oX=/^[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,iX=/^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let M0;const aX=/^(((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}))$/,lX=/^(([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})))$/,cX=e=>e.precision?e.offset?new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`):new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${e.precision}}Z$`):e.precision===0?e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$"):e.offset?new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$"):new RegExp("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$");function uX(e,t){return!!((t==="v4"||!t)&&aX.test(e)||(t==="v6"||!t)&&lX.test(e))}class di extends rt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==be.string){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.string,received:i.parsedType}),Ze}const r=new zn;let o;for(const i of this._def.checks)if(i.kind==="min")t.data.lengthi.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const s=t.data.length>i.value,l=t.data.lengtht.test(o),{validation:n,code:pe.invalid_string,...Ne.errToObj(r)})}_addCheck(t){return new di({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ne.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ne.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ne.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ne.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ne.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ne.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ne.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ne.errToObj(t)})}datetime(t){var n;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof(t==null?void 0:t.precision)>"u"?null:t==null?void 0:t.precision,offset:(n=t==null?void 0:t.offset)!==null&&n!==void 0?n:!1,...Ne.errToObj(t==null?void 0:t.message)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...Ne.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n==null?void 0:n.position,...Ne.errToObj(n==null?void 0:n.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...Ne.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...Ne.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...Ne.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...Ne.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...Ne.errToObj(n)})}nonempty(t){return this.min(1,Ne.errToObj(t))}trim(){return new di({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new di({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get minLength(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new di({checks:[],typeName:ze.ZodString,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};function dX(e,t){const n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,i=parseInt(e.toFixed(o).replace(".","")),s=parseInt(t.toFixed(o).replace(".",""));return i%s/Math.pow(10,o)}class ac extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==be.number){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.number,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="int"?mt.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?dX(t.data,i.value)!==0&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_finite,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new ac({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new ac({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ne.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:Ne.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ne.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ne.toString(t)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuet.kind==="int"||t.kind==="multipleOf"&&mt.isInteger(t.value))}get isFinite(){let t=null,n=null;for(const 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"&&(t===null||r.valuenew ac({checks:[],typeName:ze.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class lc extends rt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce&&(t.data=BigInt(t.data)),this._getType(t)!==be.bigint){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.bigint,received:i.parsedType}),Ze}let r;const o=new zn;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?t.datai.value:t.data>=i.value)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?t.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),Ee(r,{code:pe.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):mt.assertNever(i);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,Ne.toString(n))}gt(t,n){return this.setLimit("min",t,!1,Ne.toString(n))}lte(t,n){return this.setLimit("max",t,!0,Ne.toString(n))}lt(t,n){return this.setLimit("max",t,!1,Ne.toString(n))}setLimit(t,n,r,o){return new lc({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:Ne.toString(o)}]})}_addCheck(t){return new lc({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ne.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ne.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:Ne.toString(n)})}get minValue(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.value{var t;return new lc({checks:[],typeName:ze.ZodBigInt,coerce:(t=e==null?void 0:e.coerce)!==null&&t!==void 0?t:!1,...Xe(e)})};class $1 extends rt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==be.boolean){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.boolean,received:r.parsedType}),Ze}return rr(t.data)}}$1.create=e=>new $1({typeName:ze.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Xe(e)});class sd extends rt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==be.date){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_type,expected:be.date,received:i.parsedType}),Ze}if(isNaN(t.data.getTime())){const i=this._getOrReturnCtx(t);return Ee(i,{code:pe.invalid_date}),Ze}const r=new zn;let o;for(const i of this._def.checks)i.kind==="min"?t.data.getTime()i.value&&(o=this._getOrReturnCtx(t,o),Ee(o,{code:pe.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):mt.assertNever(i);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new sd({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:Ne.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:Ne.toString(n)})}get minDate(){let t=null;for(const n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const n of this._def.checks)n.kind==="max"&&(t===null||n.valuenew sd({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:ze.ZodDate,...Xe(e)});class k1 extends rt{_parse(t){if(this._getType(t)!==be.symbol){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.symbol,received:r.parsedType}),Ze}return rr(t.data)}}k1.create=e=>new k1({typeName:ze.ZodSymbol,...Xe(e)});class Gh extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.undefined,received:r.parsedType}),Ze}return rr(t.data)}}Gh.create=e=>new Gh({typeName:ze.ZodUndefined,...Xe(e)});class Xh extends rt{_parse(t){if(this._getType(t)!==be.null){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.null,received:r.parsedType}),Ze}return rr(t.data)}}Xh.create=e=>new Xh({typeName:ze.ZodNull,...Xe(e)});class R1 extends rt{constructor(){super(...arguments),this._any=!0}_parse(t){return rr(t.data)}}R1.create=e=>new R1({typeName:ze.ZodAny,...Xe(e)});class Tl extends rt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return rr(t.data)}}Tl.create=e=>new Tl({typeName:ze.ZodUnknown,...Xe(e)});class Rs extends rt{_parse(t){const n=this._getOrReturnCtx(t);return Ee(n,{code:pe.invalid_type,expected:be.never,received:n.parsedType}),Ze}}Rs.create=e=>new Rs({typeName:ze.ZodNever,...Xe(e)});class T1 extends rt{_parse(t){if(this._getType(t)!==be.undefined){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.void,received:r.parsedType}),Ze}return rr(t.data)}}T1.create=e=>new T1({typeName:ze.ZodVoid,...Xe(e)});class Uo extends rt{_parse(t){const{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==be.array)return Ee(n,{code:pe.invalid_type,expected:be.array,received:n.parsedType}),Ze;if(o.exactLength!==null){const s=n.data.length>o.exactLength.value,l=n.data.lengtho.maxLength.value&&(Ee(n,{code:pe.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,l)=>o.type._parseAsync(new Ko(n,s,n.path,l)))).then(s=>zn.mergeArray(r,s));const i=[...n.data].map((s,l)=>o.type._parseSync(new Ko(n,s,n.path,l)));return zn.mergeArray(r,i)}get element(){return this._def.type}min(t,n){return new Uo({...this._def,minLength:{value:t,message:Ne.toString(n)}})}max(t,n){return new Uo({...this._def,maxLength:{value:t,message:Ne.toString(n)}})}length(t,n){return new Uo({...this._def,exactLength:{value:t,message:Ne.toString(n)}})}nonempty(t){return this.min(1,t)}}Uo.create=(e,t)=>new Uo({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ze.ZodArray,...Xe(t)});function ol(e){if(e instanceof Vt){const t={};for(const n in e.shape){const r=e.shape[n];t[n]=bs.create(ol(r))}return new Vt({...e._def,shape:()=>t})}else return e instanceof Uo?new Uo({...e._def,type:ol(e.element)}):e instanceof bs?bs.create(ol(e.unwrap())):e instanceof uc?uc.create(ol(e.unwrap())):e instanceof _i?_i.create(e.items.map(t=>ol(t))):e}class Vt extends rt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),n=mt.objectKeys(t);return this._cached={shape:t,keys:n}}_parse(t){if(this._getType(t)!==be.object){const d=this._getOrReturnCtx(t);return Ee(d,{code:pe.invalid_type,expected:be.object,received:d.parsedType}),Ze}const{status:r,ctx:o}=this._processInputParams(t),{shape:i,keys:s}=this._getCached(),l=[];if(!(this._def.catchall instanceof Rs&&this._def.unknownKeys==="strip"))for(const d in o.data)s.includes(d)||l.push(d);const u=[];for(const d of s){const h=i[d],m=o.data[d];u.push({key:{status:"valid",value:d},value:h._parse(new Ko(o,m,o.path,d)),alwaysSet:d in o.data})}if(this._def.catchall instanceof Rs){const d=this._def.unknownKeys;if(d==="passthrough")for(const h of l)u.push({key:{status:"valid",value:h},value:{status:"valid",value:o.data[h]}});else if(d==="strict")l.length>0&&(Ee(o,{code:pe.unrecognized_keys,keys:l}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const d=this._def.catchall;for(const h of l){const m=o.data[h];u.push({key:{status:"valid",value:h},value:d._parse(new Ko(o,m,o.path,h)),alwaysSet:h in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const d=[];for(const h of u){const m=await h.key;d.push({key:m,value:await h.value,alwaysSet:h.alwaysSet})}return d}).then(d=>zn.mergeObjectSync(r,d)):zn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(t){return Ne.errToObj,new Vt({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{var o,i,s,l;const u=(s=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,n,r).message)!==null&&s!==void 0?s:r.defaultError;return n.code==="unrecognized_keys"?{message:(l=Ne.errToObj(t).message)!==null&&l!==void 0?l:u}:{message:u}}}:{}})}strip(){return new Vt({...this._def,unknownKeys:"strip"})}passthrough(){return new Vt({...this._def,unknownKeys:"passthrough"})}extend(t){return new Vt({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Vt({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:ze.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new Vt({...this._def,catchall:t})}pick(t){const n={};return mt.objectKeys(t).forEach(r=>{t[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}omit(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{t[r]||(n[r]=this.shape[r])}),new Vt({...this._def,shape:()=>n})}deepPartial(){return ol(this)}partial(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{const o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}),new Vt({...this._def,shape:()=>n})}required(t){const n={};return mt.objectKeys(this.shape).forEach(r=>{if(t&&!t[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof bs;)i=i._def.innerType;n[r]=i}}),new Vt({...this._def,shape:()=>n})}keyof(){return e3(mt.objectKeys(this.shape))}}Vt.create=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.strictCreate=(e,t)=>new Vt({shape:()=>e,unknownKeys:"strict",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});Vt.lazycreate=(e,t)=>new Vt({shape:e,unknownKeys:"strip",catchall:Rs.create(),typeName:ze.ZodObject,...Xe(t)});class Zh extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=this._def.options;function o(i){for(const l of i)if(l.result.status==="valid")return l.result;for(const l of i)if(l.result.status==="dirty")return n.common.issues.push(...l.ctx.common.issues),l.result;const s=i.map(l=>new Bo(l.ctx.common.issues));return Ee(n,{code:pe.invalid_union,unionErrors:s}),Ze}if(n.common.async)return Promise.all(r.map(async i=>{const 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;const s=[];for(const u of r){const d={...n,common:{...n.common,issues:[]},parent:null},h=u._parseSync({data:n.data,path:n.path,parent:d});if(h.status==="valid")return h;h.status==="dirty"&&!i&&(i={result:h,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const l=s.map(u=>new Bo(u));return Ee(n,{code:pe.invalid_union,unionErrors:l}),Ze}}get options(){return this._def.options}}Zh.create=(e,t)=>new Zh({options:e,typeName:ze.ZodUnion,...Xe(t)});const Zp=e=>e instanceof Jh?Zp(e.schema):e instanceof Si?Zp(e.innerType()):e instanceof em?[e.value]:e instanceof Ta?e.options:e instanceof tm?Object.keys(e.enum):e instanceof nm?Zp(e._def.innerType):e instanceof Gh?[void 0]:e instanceof Xh?[null]:null;class Yx extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.object)return Ee(n,{code:pe.invalid_type,expected:be.object,received:n.parsedType}),Ze;const 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}):(Ee(n,{code:pe.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Ze)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){const o=new Map;for(const i of n){const s=Zp(i.shape[t]);if(!s)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const l of s){if(o.has(l))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(l)}`);o.set(l,i)}}return new Yx({typeName:ze.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...Xe(r)})}}function P1(e,t){const n=ta(e),r=ta(t);if(e===t)return{valid:!0,data:e};if(n===be.object&&r===be.object){const o=mt.objectKeys(t),i=mt.objectKeys(e).filter(l=>o.indexOf(l)!==-1),s={...e,...t};for(const l of i){const u=P1(e[l],t[l]);if(!u.valid)return{valid:!1};s[l]=u.data}return{valid:!0,data:s}}else if(n===be.array&&r===be.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let i=0;i{if(T2(i)||T2(s))return Ze;const l=P1(i.value,s.value);return l.valid?((P2(i)||P2(s))&&n.dirty(),{status:n.value,value:l.data}):(Ee(r,{code:pe.invalid_intersection_types}),Ze)};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}))}}qh.create=(e,t,n)=>new qh({left:e,right:t,typeName:ze.ZodIntersection,...Xe(n)});class _i extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.array)return Ee(r,{code:pe.invalid_type,expected:be.array,received:r.parsedType}),Ze;if(r.data.lengththis._def.items.length&&(Ee(r,{code:pe.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((s,l)=>{const u=this._def.items[l]||this._def.rest;return u?u._parse(new Ko(r,s,r.path,l)):null}).filter(s=>!!s);return r.common.async?Promise.all(i).then(s=>zn.mergeArray(n,s)):zn.mergeArray(n,i)}get items(){return this._def.items}rest(t){return new _i({...this._def,rest:t})}}_i.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _i({items:e,typeName:ze.ZodTuple,rest:null,...Xe(t)})};class Qh extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.object)return Ee(r,{code:pe.invalid_type,expected:be.object,received:r.parsedType}),Ze;const o=[],i=this._def.keyType,s=this._def.valueType;for(const l in r.data)o.push({key:i._parse(new Ko(r,l,r.path,l)),value:s._parse(new Ko(r,r.data[l],r.path,l))});return r.common.async?zn.mergeObjectAsync(n,o):zn.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof rt?new Qh({keyType:t,valueType:n,typeName:ze.ZodRecord,...Xe(r)}):new Qh({keyType:di.create(),valueType:t,typeName:ze.ZodRecord,...Xe(n)})}}class A1 extends rt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.map)return Ee(r,{code:pe.invalid_type,expected:be.map,received:r.parsedType}),Ze;const o=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([l,u],d)=>({key:o._parse(new Ko(r,l,r.path,[d,"key"])),value:i._parse(new Ko(r,u,r.path,[d,"value"]))}));if(r.common.async){const l=new Map;return Promise.resolve().then(async()=>{for(const u of s){const d=await u.key,h=await u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}})}else{const l=new Map;for(const u of s){const d=u.key,h=u.value;if(d.status==="aborted"||h.status==="aborted")return Ze;(d.status==="dirty"||h.status==="dirty")&&n.dirty(),l.set(d.value,h.value)}return{status:n.value,value:l}}}}A1.create=(e,t,n)=>new A1({valueType:t,keyType:e,typeName:ze.ZodMap,...Xe(n)});class cc extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==be.set)return Ee(r,{code:pe.invalid_type,expected:be.set,received:r.parsedType}),Ze;const o=this._def;o.minSize!==null&&r.data.sizeo.maxSize.value&&(Ee(r,{code:pe.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());const i=this._def.valueType;function s(u){const d=new Set;for(const h of u){if(h.status==="aborted")return Ze;h.status==="dirty"&&n.dirty(),d.add(h.value)}return{status:n.value,value:d}}const l=[...r.data.values()].map((u,d)=>i._parse(new Ko(r,u,r.path,d)));return r.common.async?Promise.all(l).then(u=>s(u)):s(l)}min(t,n){return new cc({...this._def,minSize:{value:t,message:Ne.toString(n)}})}max(t,n){return new cc({...this._def,maxSize:{value:t,message:Ne.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}}cc.create=(e,t)=>new cc({valueType:e,minSize:null,maxSize:null,typeName:ze.ZodSet,...Xe(t)});class Pu extends rt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.function)return Ee(n,{code:pe.invalid_type,expected:be.function,received:n.parsedType}),Ze;function r(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_arguments,argumentsError:u}})}function o(l,u){return E1({data:l,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,S1(),Kh].filter(d=>!!d),issueData:{code:pe.invalid_return_type,returnTypeError:u}})}const i={errorMap:n.common.contextualErrorMap},s=n.data;if(this._def.returns instanceof ad){const l=this;return rr(async function(...u){const d=new Bo([]),h=await l._def.args.parseAsync(u,i).catch(y=>{throw d.addIssue(r(u,y)),d}),m=await Reflect.apply(s,this,h);return await l._def.returns._def.type.parseAsync(m,i).catch(y=>{throw d.addIssue(o(m,y)),d})})}else{const l=this;return rr(function(...u){const d=l._def.args.safeParse(u,i);if(!d.success)throw new Bo([r(u,d.error)]);const h=Reflect.apply(s,this,d.data),m=l._def.returns.safeParse(h,i);if(!m.success)throw new Bo([o(h,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Pu({...this._def,args:_i.create(t).rest(Tl.create())})}returns(t){return new Pu({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new Pu({args:t||_i.create([]).rest(Tl.create()),returns:n||Tl.create(),typeName:ze.ZodFunction,...Xe(r)})}}class Jh extends rt{get schema(){return this._def.getter()}_parse(t){const{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}Jh.create=(e,t)=>new Jh({getter:e,typeName:ze.ZodLazy,...Xe(t)});class em extends rt{_parse(t){if(t.data!==this._def.value){const n=this._getOrReturnCtx(t);return Ee(n,{received:n.data,code:pe.invalid_literal,expected:this._def.value}),Ze}return{status:"valid",value:t.data}}get value(){return this._def.value}}em.create=(e,t)=>new em({value:e,typeName:ze.ZodLiteral,...Xe(t)});function e3(e,t){return new Ta({values:e,typeName:ze.ZodEnum,...Xe(t)})}class Ta extends rt{_parse(t){if(typeof t.data!="string"){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{expected:mt.joinValues(r),received:n.parsedType,code:pe.invalid_type}),Ze}if(this._def.values.indexOf(t.data)===-1){const n=this._getOrReturnCtx(t),r=this._def.values;return Ee(n,{received:n.data,code:pe.invalid_enum_value,options:r}),Ze}return rr(t.data)}get options(){return this._def.values}get enum(){const t={};for(const n of this._def.values)t[n]=n;return t}get Values(){const t={};for(const n of this._def.values)t[n]=n;return t}get Enum(){const t={};for(const n of this._def.values)t[n]=n;return t}extract(t){return Ta.create(t)}exclude(t){return Ta.create(this.options.filter(n=>!t.includes(n)))}}Ta.create=e3;class tm extends rt{_parse(t){const n=mt.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==be.string&&r.parsedType!==be.number){const o=mt.objectValues(n);return Ee(r,{expected:mt.joinValues(o),received:r.parsedType,code:pe.invalid_type}),Ze}if(n.indexOf(t.data)===-1){const o=mt.objectValues(n);return Ee(r,{received:r.data,code:pe.invalid_enum_value,options:o}),Ze}return rr(t.data)}get enum(){return this._def.values}}tm.create=(e,t)=>new tm({values:e,typeName:ze.ZodNativeEnum,...Xe(t)});class ad extends rt{unwrap(){return this._def.type}_parse(t){const{ctx:n}=this._processInputParams(t);if(n.parsedType!==be.promise&&n.common.async===!1)return Ee(n,{code:pe.invalid_type,expected:be.promise,received:n.parsedType}),Ze;const r=n.parsedType===be.promise?n.data:Promise.resolve(n.data);return rr(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}}ad.create=(e,t)=>new ad({type:e,typeName:ze.ZodPromise,...Xe(t)});class Si extends rt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ze.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,i={addIssue:s=>{Ee(r,s),s.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){const s=o.transform(r.data,i);return r.common.issues.length?{status:"dirty",value:r.data}:r.common.async?Promise.resolve(s).then(l=>this._def.schema._parseAsync({data:l,path:r.path,parent:r})):this._def.schema._parseSync({data:s,path:r.path,parent:r})}if(o.type==="refinement"){const s=l=>{const u=o.refinement(l,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return l};if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value),{status:n.value,value:l.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>l.status==="aborted"?Ze:(l.status==="dirty"&&n.dirty(),s(l.value).then(()=>({status:n.value,value:l.value}))))}if(o.type==="transform")if(r.common.async===!1){const s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Yh(s))return s;const l=o.transform(s.value,i);if(l instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:l}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>Yh(s)?Promise.resolve(o.transform(s.value,i)).then(l=>({status:n.value,value:l})):s);mt.assertNever(o)}}Si.create=(e,t,n)=>new Si({schema:e,typeName:ze.ZodEffects,effect:t,...Xe(n)});Si.createWithPreprocess=(e,t,n)=>new Si({schema:t,effect:{type:"preprocess",transform:e},typeName:ze.ZodEffects,...Xe(n)});class bs extends rt{_parse(t){return this._getType(t)===be.undefined?rr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}bs.create=(e,t)=>new bs({innerType:e,typeName:ze.ZodOptional,...Xe(t)});class uc extends rt{_parse(t){return this._getType(t)===be.null?rr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}uc.create=(e,t)=>new uc({innerType:e,typeName:ze.ZodNullable,...Xe(t)});class nm extends rt{_parse(t){const{ctx:n}=this._processInputParams(t);let r=n.data;return n.parsedType===be.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}}nm.create=(e,t)=>new nm({innerType:e,typeName:ze.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});class O1 extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return C1(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Bo(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}O1.create=(e,t)=>new O1({innerType:e,typeName:ze.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});class M1 extends rt{_parse(t){if(this._getType(t)!==be.nan){const r=this._getOrReturnCtx(t);return Ee(r,{code:pe.invalid_type,expected:be.nan,received:r.parsedType}),Ze}return{status:"valid",value:t.data}}}M1.create=e=>new M1({typeName:ze.ZodNaN,...Xe(e)});class fX extends rt{_parse(t){const{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class sg extends rt{_parse(t){const{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Ze:i.status==="dirty"?(n.dirty(),eX(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ze:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new sg({in:t,out:n,typeName:ze.ZodPipeline})}}class N1 extends rt{_parse(t){const n=this._def.innerType._parse(t);return Yh(n)&&(n.value=Object.freeze(n.value)),n}}N1.create=(e,t)=>new N1({innerType:e,typeName:ze.ZodReadonly,...Xe(t)});Vt.lazycreate;var ze;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(ze||(ze={}));const O2=di.create;ac.create;M1.create;lc.create;const su=$1.create;sd.create;k1.create;Gh.create;Xh.create;R1.create;Tl.create;Rs.create;T1.create;Uo.create;const pX=Vt.create;Vt.strictCreate;Zh.create;Yx.create;qh.create;_i.create;Qh.create;A1.create;cc.create;Pu.create;Jh.create;em.create;Ta.create;tm.create;ad.create;Si.create;bs.create;uc.create;Si.createWithPreprocess;sg.create;const D1="horizontal",hX=["horizontal","vertical"],t3=f.forwardRef((e,t)=>{const{decorative:n,orientation:r=D1,...o}=e,i=n3(r)?r:D1,l=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return f.createElement(Pe.div,Y({"data-orientation":i},l,o,{ref:t}))});t3.propTypes={orientation(e,t,n){const r=e[t],o=String(r);return r&&!n3(r)?new Error(mX(o,n)):null}};function mX(e,t){return`Invalid prop \`orientation\` of value \`${e}\` supplied to \`${t}\`, expected one of: + - horizontal + - vertical + +Defaulting to \`${D1}\`.`}function n3(e){return hX.includes(e)}const r3=t3,Fn=f.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>v.jsx(r3,{ref:o,decorative:n,orientation:t,className:Ce("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Fn.displayName=r3.displayName;const gX=f.forwardRef((e,t)=>f.createElement(Pe.label,Y({},e,{ref:t,onMouseDown:n=>{var r;(r=e.onMouseDown)===null||r===void 0||r.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault()}}))),o3=gX,vX=Om("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Gx=f.forwardRef(({className:e,disabled:t,...n},r)=>v.jsx(o3,{ref:r,className:Ce(vX(),e,t?"opacity-50":"","select-none"),...n}));Gx.displayName=o3.displayName;const yX=OG,i3=f.createContext({}),N0=({...e})=>v.jsx(i3.Provider,{value:{name:e.name},children:v.jsx(IG,{...e})}),ag=()=>{const e=f.useContext(i3),t=f.useContext(s3),{getFieldState:n,formState:r}=ig(),o=n(e.name,r);if(!e)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:e.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...o}},s3=f.createContext({}),qp=f.forwardRef(({className:e,...t},n)=>{const r=f.useId();return v.jsx(s3.Provider,{value:{id:r},children:v.jsx("div",{ref:n,className:Ce("space-y-2",e),...t})})});qp.displayName="FormItem";const Qp=f.forwardRef(({className:e,...t},n)=>{const{error:r,formItemId:o}=ag();return v.jsx(Gx,{ref:n,className:Ce(r&&"text-destructive","text-sm",e),htmlFor:o,...t})});Qp.displayName="FormLabel";const Jp=f.forwardRef(({...e},t)=>{const{error:n,formItemId:r,formDescriptionId:o,formMessageId:i}=ag();return v.jsx(Wo,{ref:t,id:r,"aria-describedby":n?`${o} ${i}`:`${o}`,"aria-invalid":!!n,...e})});Jp.displayName="FormControl";const eh=f.forwardRef(({className:e,...t},n)=>{const{formDescriptionId:r}=ag();return v.jsx("p",{ref:n,id:r,className:Ce("text-[0.8rem] text-muted-foreground",e),...t})});eh.displayName="FormDescription";const wX=f.forwardRef(({className:e,children:t,...n},r)=>{const{error:o,formMessageId:i}=ag(),s=o?String(o==null?void 0:o.message):t;return s?v.jsx("p",{ref:r,id:i,className:Ce("text-[0.8rem] font-medium text-destructive",e),...n,children:s}):null});wX.displayName="FormMessage";const a3="Switch",[xX,_te]=An(a3),[bX,_X]=xX(a3),SX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:i,required:s,disabled:l,value:u="on",onCheckedChange:d,...h}=e,[m,g]=f.useState(null),y=Be(t,b=>g(b)),x=f.useRef(!1),_=m?!!m.closest("form"):!0,[C=!1,S]=Zr({prop:o,defaultProp:i,onChange:d});return f.createElement(bX,{scope:n,checked:C,disabled:l},f.createElement(Pe.button,Y({type:"button",role:"switch","aria-checked":C,"aria-required":s,"data-state":l3(C),"data-disabled":l?"":void 0,disabled:l,value:u},h,{ref:y,onClick:ue(e.onClick,b=>{S(E=>!E),_&&(x.current=b.isPropagationStopped(),x.current||b.stopPropagation())})})),_&&f.createElement($X,{control:m,bubbles:!x.current,name:r,value:u,checked:C,required:s,disabled:l,style:{transform:"translateX(-100%)"}}))}),EX="SwitchThumb",CX=f.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=_X(EX,n);return f.createElement(Pe.span,Y({"data-state":l3(o.checked),"data-disabled":o.disabled?"":void 0},r,{ref:t}))}),$X=e=>{const{control:t,checked:n,bubbles:r=!0,...o}=e,i=f.useRef(null),s=Fx(n),l=gx(t);return f.useEffect(()=>{const u=i.current,d=window.HTMLInputElement.prototype,m=Object.getOwnPropertyDescriptor(d,"checked").set;if(s!==n&&m){const g=new Event("click",{bubbles:r});m.call(u,n),u.dispatchEvent(g)}},[s,n,r]),f.createElement("input",Y({type:"checkbox","aria-hidden":!0,defaultChecked:n},o,{tabIndex:-1,ref:i,style:{...e.style,...l,position:"absolute",pointerEvents:"none",opacity:0,margin:0}}))};function l3(e){return e?"checked":"unchecked"}const c3=SX,kX=CX,co=f.forwardRef(({className:e,...t},n)=>v.jsx(c3,{className:Ce("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),tabIndex:-1,...t,ref:n,children:v.jsx(kX,{className:Ce("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));co.displayName=c3.displayName;const RX="AlertDialog",[TX,Ste]=An(RX,[cP]),Is=cP(),PX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Sx,Y({},r,n,{modal:!0}))},AX=e=>{const{__scopeAlertDialog:t,...n}=e,r=Is(t);return f.createElement(Ex,Y({},r,n))},OX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Nd,Y({},o,r,{ref:t}))}),u3="AlertDialogContent",[MX,NX]=TX(u3),DX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,children:r,...o}=e,i=Is(n),s=f.useRef(null),l=Be(t,s),u=f.useRef(null);return f.createElement(fW,{contentName:u3,titleName:IX,docsSlug:"alert-dialog"},f.createElement(MX,{scope:n,cancelRef:u},f.createElement(Dd,Y({role:"alertdialog"},i,o,{ref:l,onOpenAutoFocus:ue(o.onOpenAutoFocus,d=>{var h;d.preventDefault(),(h=u.current)===null||h===void 0||h.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault()}),f.createElement(sx,null,r),!1)))}),IX="AlertDialogTitle",LX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Id,Y({},o,r,{ref:t}))}),FX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Ld,Y({},o,r,{ref:t}))}),jX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,o=Is(n);return f.createElement(Cx,Y({},o,r,{ref:t}))}),zX="AlertDialogCancel",BX=f.forwardRef((e,t)=>{const{__scopeAlertDialog:n,...r}=e,{cancelRef:o}=NX(zX,n),i=Is(n),s=Be(t,o);return f.createElement(Cx,Y({},i,r,{ref:s}))}),UX=PX,VX=AX,d3=OX,f3=DX,p3=jX,h3=BX,m3=LX,g3=FX,WX=UX,HX=VX,v3=f.forwardRef(({className:e,...t},n)=>v.jsx(d3,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));v3.displayName=d3.displayName;const y3=f.forwardRef(({className:e,...t},n)=>v.jsxs(HX,{children:[v.jsx(v3,{}),v.jsx(f3,{ref:n,className:Ce("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",e),...t})]}));y3.displayName=f3.displayName;const w3=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});w3.displayName="AlertDialogHeader";const KX=f.forwardRef(({className:e,...t},n)=>v.jsx(m3,{ref:n,className:Ce("text-lg font-semibold",e),...t}));KX.displayName=m3.displayName;const YX=f.forwardRef(({className:e,...t},n)=>v.jsx(g3,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));YX.displayName=g3.displayName;const GX=f.forwardRef(({className:e,...t},n)=>v.jsx(p3,{ref:n,className:Ce(bx(),e),...t}));GX.displayName=p3.displayName;const XX=f.forwardRef(({className:e,...t},n)=>v.jsx(h3,{ref:n,className:Ce(bx({variant:"outline"}),"mt-2 sm:mt-0",e),...t}));XX.displayName=h3.displayName;const ZX=pX({enableFileManager:su(),inputDirectory:O2(),outputDirectory:O2(),enableDownloadMask:su(),enableManualInpainting:su(),enableUploadMask:su(),enableAutoExtractPrompt:su()}),x3="General",I1="Model",qX=[I1,x3];function QX(){const[e,t]=u1(!1),[n,r]=u1(!1),[o,i]=f.useState(I1),[s,l,u,d,h,m]=bt(O=>[O.updateAppState,O.settings,O.updateSettings,O.fileManagerState,O.updateFileManagerState,O.setModel]),{toast:g}=Td(),[y,x]=f.useState(l.model);f.useEffect(()=>{x(l.model)},[l.model]);const{data:_,status:C}=TL({queryKey:["modelInfos"],queryFn:Bj}),S=YG({resolver:QG(ZX),defaultValues:{enableDownloadMask:l.enableDownloadMask,enableManualInpainting:l.enableManualInpainting,enableUploadMask:l.enableUploadMask,enableAutoExtractPrompt:l.enableAutoExtractPrompt,inputDirectory:d.inputDirectory,outputDirectory:d.outputDirectory}});async function b(O){if(u({enableDownloadMask:O.enableDownloadMask,enableManualInpainting:O.enableManualInpainting,enableUploadMask:O.enableUploadMask,enableAutoExtractPrompt:O.enableAutoExtractPrompt}),h({inputDirectory:O.inputDirectory,outputDirectory:O.outputDirectory}),y.name!==l.model.name){r(),s({disableShortCuts:!0});try{const F=await jj(y.name);g({title:`Switch to ${F.name} success`}),m(y)}catch(F){g({variant:"destructive",title:`Switch to ${y.name} failed: ${F}`}),x(l.model)}finally{r(),s({disableShortCuts:!1})}}}Zn("s",()=>{t(),e&&b(S.getValues())},[e,S,y]);function E(O){t(),O||b(S.getValues())}function k(O){x(O)}function P(O){return _?_.filter(F=>O.includes(F.model_type)).map(F=>v.jsxs("div",{onClick:()=>k(F),className:"px-2",children:[v.jsx("div",{className:Ce([F.name===y.name?"bg-muted":"hover:bg-muted","rounded-md px-2 py-2","cursor-default"]),children:v.jsx("div",{className:"text-base",children:F.name})}),v.jsx(Fn,{className:"my-1"})]},F.name)):v.jsx("div",{children:"Please download model first"})}function M(){if(C!=="success")return v.jsx(v.Fragment,{});let O=is;for(let F of _)if(y.name===F.name){O=F.model_type,O===nC&&(O=rp),O===rC&&(O=op);break}return v.jsxs("div",{className:"flex flex-col gap-4 w-[510px]",children:[v.jsxs("div",{className:"flex flex-col gap-4 rounded-md",children:[v.jsx("div",{className:"font-medium",children:"Current Model"}),v.jsx("div",{children:y.name})]}),v.jsx(Fn,{}),v.jsxs("div",{className:"space-y-4 rounded-md",children:[v.jsx("div",{className:"flex gap-1 items-center justify-start",children:v.jsx("div",{className:"font-medium",children:"Available models"})}),v.jsxs(i5,{defaultValue:O,children:[v.jsxs(Lx,{children:[v.jsx(sa,{value:is,children:"Inpaint"}),v.jsx(sa,{value:rp,children:"Stable Diffusion"}),v.jsx(sa,{value:op,children:"Stable Diffusion Inpaint"}),v.jsx(sa,{value:l0,children:"Other Diffusion"})]}),v.jsxs(og,{className:"h-[240px] w-full mt-2 outline-none border rounded-lg",children:[v.jsx(mu,{value:is,children:P([is])}),v.jsx(mu,{value:rp,children:P([rp,nC])}),v.jsx(mu,{value:op,children:P([op,rC])}),v.jsx(mu,{value:l0,children:P([l0])})]})]})]})]})}function A(){return v.jsxs("div",{className:"space-y-4 w-[510px]",children:[v.jsx(N0,{control:S.control,name:"enableManualInpainting",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable manual inpainting"}),v.jsx(eh,{children:"For erase model, click a button to trigger inpainting after draw mask."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableDownloadMask",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable download mask"}),v.jsx(eh,{children:"Also download the mask after save the inpainting result."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})}),v.jsx(Fn,{}),v.jsx(N0,{control:S.control,name:"enableAutoExtractPrompt",render:({field:O})=>v.jsxs(qp,{className:"flex items-center justify-between",children:[v.jsxs("div",{className:"space-y-0.5",children:[v.jsx(Qp,{children:"Enable auto extract prompt"}),v.jsx(eh,{children:"Automatically extract prompt/negativate prompt from the image meta."})]}),v.jsx(Jp,{children:v.jsx(co,{checked:O.value,onCheckedChange:O.onChange})})]})})]})}return v.jsxs(v.Fragment,{children:[v.jsx(WX,{open:n,children:v.jsx(y3,{children:v.jsx(w3,{children:v.jsxs("div",{className:"flex flex-col justify-center items-center gap-4",children:[v.jsxs("div",{role:"status",children:[v.jsxs("svg",{"aria-hidden":"true",className:"w-8 h-8 text-gray-200 animate-spin dark:text-gray-600 fill-primary",viewBox:"0 0 100 101",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[v.jsx("path",{d:"M100 50.5908C100 78.2051 77.6142 100.591 50 100.591C22.3858 100.591 0 78.2051 0 50.5908C0 22.9766 22.3858 0.59082 50 0.59082C77.6142 0.59082 100 22.9766 100 50.5908ZM9.08144 50.5908C9.08144 73.1895 27.4013 91.5094 50 91.5094C72.5987 91.5094 90.9186 73.1895 90.9186 50.5908C90.9186 27.9921 72.5987 9.67226 50 9.67226C27.4013 9.67226 9.08144 27.9921 9.08144 50.5908Z",fill:"currentColor"}),v.jsx("path",{d:"M93.9676 39.0409C96.393 38.4038 97.8624 35.9116 97.0079 33.5539C95.2932 28.8227 92.871 24.3692 89.8167 20.348C85.8452 15.1192 80.8826 10.7238 75.2124 7.41289C69.5422 4.10194 63.2754 1.94025 56.7698 1.05124C51.7666 0.367541 46.6976 0.446843 41.7345 1.27873C39.2613 1.69328 37.813 4.19778 38.4501 6.62326C39.0873 9.04874 41.5694 10.4717 44.0505 10.1071C47.8511 9.54855 51.7191 9.52689 55.5402 10.0491C60.8642 10.7766 65.9928 12.5457 70.6331 15.2552C75.2735 17.9648 79.3347 21.5619 82.5849 25.841C84.9175 28.9121 86.7997 32.2913 88.1811 35.8758C89.083 38.2158 91.5421 39.6781 93.9676 39.0409Z",fill:"currentFill"})]}),v.jsx("span",{className:"sr-only",children:"Loading..."})]}),v.jsxs("div",{children:["Switching to ",y.name]})]})})})}),v.jsxs(Zm,{open:e,onOpenChange:E,children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Settings",children:v.jsx(iV,{})})}),v.jsxs(Fd,{className:"max-w-3xl h-[600px]",onOpenAutoFocus:O=>O.preventDefault(),children:[v.jsx(jd,{children:"Settings"}),v.jsx(Fn,{}),v.jsxs("div",{className:"flex flex-row space-x-8 h-full",children:[v.jsx("div",{className:"flex flex-col space-y-1",children:qX.map(O=>v.jsx(yn,{variant:"ghost",onClick:()=>i(O),className:Ce(o===O?"bg-muted ":"hover:bg-muted","justify-start"),children:O},O))}),v.jsx(Fn,{orientation:"vertical"}),v.jsx(yX,{...S,children:v.jsx("div",{className:"flex w-full justify-center",children:v.jsxs("form",{onSubmit:S.handleSubmit(b),children:[o===I1?M():v.jsx(v.Fragment,{}),o===x3?A():v.jsx(v.Fragment,{}),v.jsx("div",{className:"absolute right-10 bottom-6",children:v.jsx(yn,{onClick:()=>E(!1),children:"Ok"})})]})})})]})]})]})]})}const JX="/assets/kofi_button_black-XI_Dr2zg.png";function eZ(){return v.jsxs(Zm,{children:[v.jsx($x,{asChild:!0,children:v.jsx(vn,{tooltip:"Buy me a coffee",children:v.jsx(GU,{})})}),v.jsxs(Fd,{children:[v.jsx(jd,{children:"Buy me a coffee"}),v.jsx(mP,{className:"mb-8",children:"Hi, if you found my project is useful, please conside buy me a coffee to support my work. Thanks!"}),v.jsx("div",{className:"w-full flex items-center justify-center",children:v.jsx("a",{href:"https://ko-fi.com/Z8Z1CZJGY",target:"_blank",rel:"noreferrer",children:v.jsx("img",{src:JX,className:"h-[32px]"})})})]})]})}const tZ=()=>{const[e,t,n,r,o,i,s,l,u,d,h,m,g,y]=bt(M=>[M.file,M.customMask,M.isInpainting,M.serverConfig,M.runMannually(),M.settings.enableUploadMask,M.settings.model,M.setFile,M.setCustomFile,M.runInpainting,M.showPrevMask,M.hidePrevMask,M.imageHeight,M.imageWidth]),{toast:x}=Td(),[_,C]=Rx(t),[S,b]=f.useState(!1),E=()=>{d()},k=()=>{h()},P=()=>{m()};return v.jsxs("header",{className:"h-[60px] px-6 py-4 absolute top-[0] flex justify-between items-center w-full z-20 border-b backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsxs("div",{className:"flex items-center gap-1",children:[r.enableFileManager?v.jsx(TG,{photoWidth:512,onPhotoClick:async(M,A)=>{try{const O=await Uj(M,A);l(O)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}}}):v.jsx(v.Fragment,{}),v.jsx(c1,{disabled:n,tooltip:"Upload image",onFileUpload:M=>{l(M)},children:v.jsx(eV,{})}),v.jsxs("div",{className:Ce(["flex items-center gap-1",e&&i?"visible":"hidden"]),children:[v.jsx(c1,{disabled:n,tooltip:"Upload custom mask",onFileUpload:async M=>{let A=null;try{A=await pF(M)}catch(O){x({variant:"destructive",description:O.message?O.message:O.toString()});return}if(A.naturalHeight!==g||A.naturalWidth!==y){x({variant:"destructive",description:`The size of the mask must same as image: ${y}x${g}`});return}u(M),o||d()},children:v.jsx(ZT,{})}),t?v.jsxs(HW,{open:S,children:[v.jsx(KW,{className:"btn-primary side-panel-trigger",onMouseEnter:()=>b(!0),onMouseLeave:()=>b(!1),style:{visibility:t?"visible":"hidden",outline:"none"},onClick:()=>{},children:v.jsx(vn,{tooltip:"Run custom mask",children:v.jsx(cz,{})})}),v.jsx(PP,{children:C?v.jsx("img",{src:_.src,alt:"Custom mask"}):v.jsx(v.Fragment,{})})]}):v.jsx(v.Fragment,{})]}),e&&!s.need_prompt?v.jsx(vn,{disabled:n,tooltip:"Rerun previous mask",onClick:E,onMouseEnter:k,onMouseLeave:P,children:v.jsx(oV,{})}):v.jsx(v.Fragment,{})]}),s.need_prompt?v.jsx(vH,{}):v.jsx(v.Fragment,{}),v.jsxs("div",{className:"flex gap-1",children:[v.jsx(eZ,{}),v.jsx(AW,{}),r.disableModelSwitch?v.jsx(v.Fragment,{}):v.jsx(QX,{})]})]})};var Wr=function(e,t){return Number(e.toFixed(t))},nZ=function(e,t){return typeof e=="number"?e:t},Nt=function(e,t,n){n&&typeof n=="function"&&n(e,t)},rZ=function(e){return-Math.cos(e*Math.PI)/2+.5},oZ=function(e){return e},iZ=function(e){return e*e},sZ=function(e){return e*(2-e)},aZ=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},lZ=function(e){return e*e*e},cZ=function(e){return--e*e*e+1},uZ=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},dZ=function(e){return e*e*e*e},fZ=function(e){return 1- --e*e*e*e},pZ=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},hZ=function(e){return e*e*e*e*e},mZ=function(e){return 1+--e*e*e*e*e},gZ=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b3={easeOut:rZ,linear:oZ,easeInQuad:iZ,easeOutQuad:sZ,easeInOutQuad:aZ,easeInCubic:lZ,easeOutCubic:cZ,easeInOutCubic:uZ,easeInQuart:dZ,easeOutQuart:fZ,easeInOutQuart:pZ,easeInQuint:hZ,easeOutQuint:mZ,easeInOutQuint:gZ},_3=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Do=function(e){e.mounted&&(_3(e.animation),e.animate=!1,e.animation=null,e.velocity=null)};function S3(e,t,n,r){if(e.mounted){var o=new Date().getTime(),i=1;Do(e),e.animation=function(){if(!e.mounted)return _3(e.animation);var s=new Date().getTime()-o,l=s/n,u=b3[t],d=u(l);s>=n?(r(i),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function vZ(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function Ls(e,t,n,r){var o=vZ(t);if(!(!e.mounted||!o)){var i=e.setTransformState,s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=t.scale-l,m=t.positionX-u,g=t.positionY-d;n===0?i(t.scale,t.positionX,t.positionY):S3(e,r,n,function(y){var x=l+h*y,_=u+m*y,C=d+g*y;i(x,_,C)})}}function yZ(e,t,n){var r=e.offsetWidth,o=e.offsetHeight,i=t.offsetWidth,s=t.offsetHeight,l=i*n,u=s*n,d=r-l,h=o-u;return{wrapperWidth:r,wrapperHeight:o,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:h}}var wZ=function(e,t,n,r,o,i,s){var l=e>t?n*(s?1:.5):0,u=r>o?i*(s?1:.5):0,d=e-t-l,h=l,m=r-o-u,g=u;return{minPositionX:d,maxPositionX:h,minPositionY:m,maxPositionY:g}},Xx=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,o=e.setup.centerZoomedOut;if(!n||!r)throw new Error("Components are not mounted");var i=yZ(n,r,t),s=i.wrapperWidth,l=i.wrapperHeight,u=i.newContentWidth,d=i.newDiffWidth,h=i.newContentHeight,m=i.newDiffHeight,g=wZ(s,u,d,l,h,m,!!o);return g},L1=function(e,t,n,r){return r?en?Wr(n,2):Wr(e,2):Wr(e,2)},dc=function(e,t){var n=Xx(e,t);return e.bounds=n,n};function lg(e,t,n,r,o,i,s){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,h=n.maxPositionY,m=0,g=0;s&&(m=o,g=i);var y=L1(e,l-m,d+m,r),x=L1(t,u-g,h+g,r);return{x:y,y:x}}function cg(e,t,n,r,o,i){var s=e.transformState,l=s.scale,u=s.positionX,d=s.positionY,h=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var m=u-t*h,g=d-n*h,y=lg(m,g,o,i,0,0,null);return y}function Vd(e,t,n,r,o){var i=o?r:0,s=t-i;return!Number.isNaN(n)&&e>=n?n:!Number.isNaN(t)&&e<=s?s:e}var M2=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,o=e.wrapperComponent,i=t.target,s=o==null?void 0:o.contains(i),l=r&&i&&s;if(!l)return!1;var u=ug(i,n);return!u},N2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,o=r.panning.disabled,i=t&&n&&!o;return!!i},xZ=function(e,t){var n=e.transformState,r=n.positionX,o=n.positionY;e.isPanning=!0;var i=t.clientX,s=t.clientY;e.startCoords={x:i-r,y:s-o}},bZ=function(e,t){var n=t.touches,r=e.transformState,o=r.positionX,i=r.positionY;e.isPanning=!0;var s=n.length===1;if(s){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-o,y:u-i}}};function _Z(e){var t=e.transformState,n=t.positionX,r=t.positionY,o=t.scale,i=e.setup,s=i.disabled,l=i.limitToBounds,u=i.centerZoomedOut,d=e.wrapperComponent;if(!(s||!d||!e.bounds)){var h=e.bounds,m=h.maxPositionX,g=h.minPositionX,y=h.maxPositionY,x=h.minPositionY,_=n>m||ny||rm?d.offsetWidth:e.setup.minPositionX||0,b=r>y?d.offsetHeight:e.setup.minPositionY||0,E=cg(e,S,b,o,e.bounds,l||u),k=E.x,P=E.y;return{scale:o,positionX:_?k:n,positionY:C?P:r}}}function SZ(e,t,n,r,o){var i=e.setup.limitToBounds,s=e.wrapperComponent,l=e.bounds,u=e.transformState,d=u.scale,h=u.positionX,m=u.positionY;if(!(s===null||l===null||t===h&&n===m)){var g=lg(t,n,l,i,r,o,s),y=g.x,x=g.y;e.setTransformState(d,y,x)}}var EZ=function(e,t,n){var r=e.startCoords,o=e.transformState,i=e.setup.panning,s=i.lockAxisX,l=i.lockAxisY,u=o.positionX,d=o.positionY;if(!r)return{x:u,y:d};var h=t-r.x,m=n-r.y,g=s?u:h,y=l?d:m;return{x:g,y}},rm=function(e,t){var n=e.setup,r=e.transformState,o=r.scale,i=n.minScale,s=n.disablePadding;return t>0&&o>=i&&!s?t:0},CZ=function(e){var t=e.mounted,n=e.setup,r=n.disabled,o=n.velocityAnimation,i=e.transformState.scale,s=o.disabled,l=!s||i>1||!r||t;return!!l},$Z=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,o=e.setup,i=o.disabled,s=o.velocityAnimation,l=e.transformState.scale,u=s.disabled,d=!u||l>1||!i||t;return!(!d||!n||!r)};function kZ(e,t){var n=e.setup.velocityAnimation,r=n.equalToMove,o=n.animationTime,i=n.sensitivity;return r?o*t*i:o}function D2(e,t,n,r,o,i,s,l,u,d){if(o){if(t>s&&n>s){var h=s+(e-s)*d;return h>u?u:hi?i:h}}return r?t:L1(e,i,s,o)}function RZ(e,t){var n=1;return t?Math.min(n,e.offsetWidth/window.innerWidth):n}function TZ(e,t){var n=CZ(e);if(n){var r=e.lastMousePosition,o=e.velocityTime,i=e.setup,s=e.wrapperComponent,l=i.velocityAnimation.equalToMove,u=Date.now();if(r&&o&&s){var d=RZ(s,l),h=t.x-r.x,m=t.y-r.y,g=h/d,y=m/d,x=u-o,_=h*h+m*m,C=Math.sqrt(_)/x;e.velocity={velocityX:g,velocityY:y,total:C}}e.lastMousePosition=t,e.velocityTime=u}}function PZ(e){var t=e.velocity,n=e.bounds,r=e.setup,o=e.wrapperComponent,i=$Z(e);if(!(!i||!t||!n||!o)){var s=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,h=n.minPositionX,m=n.maxPositionY,g=n.minPositionY,y=r.limitToBounds,x=r.alignmentAnimation,_=r.zoomAnimation,C=r.panning,S=C.lockAxisY,b=C.lockAxisX,E=_.animationType,k=x.sizeX,P=x.sizeY,M=x.velocityAlignmentTime,A=M,O=kZ(e,u),F=Math.max(O,A),V=rm(e,k),J=rm(e,P),G=V*o.offsetWidth/100,ae=J*o.offsetHeight/100,U=d+G,te=h-G,L=m+ae,ie=g-ae,K=e.transformState,Q=new Date().getTime();S3(e,E,F,function(W){var le=e.transformState,ge=le.scale,Ve=le.positionX,Ue=le.positionY,We=new Date().getTime()-Q,Me=We/A,fe=b3[x.animationType],xe=1-fe(Math.min(1,Me)),$e=1-W,Ae=Ve+s*$e,Oe=Ue+l*$e,je=D2(Ae,K.positionX,Ve,b,y,h,d,te,U,xe),Ot=D2(Oe,K.positionY,Ue,S,y,g,m,ie,L,xe);(Ve!==Ae||Ue!==Oe)&&e.setTransformState(ge,je,Ot)})}}function I2(e,t){var n=e.transformState.scale;Do(e),dc(e,n),window.TouchEvent!==void 0&&t instanceof TouchEvent?bZ(e,t):xZ(e,t)}function E3(e){var t=e.transformState.scale,n=e.setup,r=n.minScale,o=n.alignmentAnimation,i=o.disabled,s=o.sizeX,l=o.sizeY,u=o.animationTime,d=o.animationType,h=i||t.1&&m;g?PZ(e):E3(e)}}function Zx(e,t,n,r){var o=e.setup,i=o.minScale,s=o.maxScale,l=o.limitToBounds,u=Vd(Wr(t,2),i,s,0,!1),d=dc(e,u),h=cg(e,n,r,u,d,l),m=h.x,g=h.y;return{scale:u,positionX:m,positionY:g}}function C3(e,t,n){var r=e.transformState.scale,o=e.wrapperComponent,i=e.setup,s=i.minScale,l=i.limitToBounds,u=i.zoomAnimation,d=u.disabled,h=u.animationTime,m=u.animationType,g=d||r>=s;if((r>=1||l)&&E3(e),!(g||!o||!e.mounted)){var y=t||o.offsetWidth/2,x=n||o.offsetHeight/2,_=Zx(e,s,y,x);_&&Ls(e,_,h,m)}}var _s=function(){return _s=Object.assign||function(t){for(var n,r=1,o=arguments.length;rs||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaYt.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},GZ=function(e,t){var n=e.setup.pinch,r=n.disabled,o=n.excluded,i=e.isInitialized,s=t.target,l=i&&!r&&s;if(!l)return!1;var u=ug(s,o);return!u},XZ=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,o=n&&!t&&r;return!!o},ZZ=function(e,t,n){var r=n.getBoundingClientRect(),o=e.touches,i=Wr(o[0].clientX-r.left,5),s=Wr(o[0].clientY-r.top,5),l=Wr(o[1].clientX-r.left,5),u=Wr(o[1].clientY-r.top,5);return{x:(i+l)/2/t,y:(s+u)/2/t}},O3=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},qZ=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,o=e.setup,i=o.maxScale,s=o.minScale,l=o.zoomAnimation,u=o.disablePadding,d=l.size,h=l.disabled;if(!n||r===null||!t)throw new Error("Pinch touches distance was not provided");if(t<0)return e.transformState.scale;var m=t/r,g=m*n;return Vd(Wr(g,2),s,i,d,!h&&!u)},QZ=160,JZ=100,eq=function(e,t){var n=e.props,r=n.onWheelStart,o=n.onZoomStart;e.wheelStopEventTimer||(Do(e),Nt(St(e),t,r),Nt(St(e),t,o))},tq=function(e,t){var n=e.props,r=n.onWheel,o=n.onZoom,i=e.contentComponent,s=e.setup,l=e.transformState,u=l.scale,d=s.limitToBounds,h=s.centerZoomedOut,m=s.zoomAnimation,g=s.wheel,y=s.disablePadding,x=s.smooth,_=m.size,C=m.disabled,S=g.step,b=g.smoothStep;if(!i)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var E=HZ(t,null),k=x?b*Math.abs(t.deltaY):S,P=KZ(e,E,k,!t.ctrlKey);if(u!==P){var M=dc(e,P),A=A3(t,i,u),O=C||_===0||h||y,F=d&&O,V=cg(e,A.x,A.y,P,M,F),J=V.x,G=V.y;e.previousWheelEvent=t,e.setTransformState(P,J,G),Nt(St(e),t,r),Nt(St(e),t,o)}},nq=function(e,t){var n=e.props,r=n.onWheelStop,o=n.onZoomStop;j1(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(C3(e,t.x,t.y),e.wheelAnimationTimer=null)},JZ);var i=YZ(e,t);i&&(j1(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Nt(St(e),t,r),Nt(St(e),t,o))},QZ))},rq=function(e,t){var n=O3(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.transformState.scale,e.isPanning=!1,Do(e)},oq=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,o=e.transformState.scale,i=e.setup,s=i.limitToBounds,l=i.centerZoomedOut,u=i.zoomAnimation,d=u.disabled,h=u.size;if(!(r===null||!n)){var m=ZZ(t,o,n);if(!(!Number.isFinite(m.x)||!Number.isFinite(m.y))){var g=O3(t),y=qZ(e,g);if(y!==o){var x=dc(e,y),_=d||h===0||l,C=s&&_,S=cg(e,m.x,m.y,y,x,C),b=S.x,E=S.y;e.pinchMidpoint=m,e.lastDistance=g,e.setTransformState(y,b,E)}}}},iq=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,C3(e,t==null?void 0:t.x,t==null?void 0:t.y)},M3=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;j1(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Nt(St(e),t,n)},r)},sq=function(e,t){var n=e.props,r=n.onZoomStart,o=n.onZoom,i=e.setup.doubleClick,s=i.animationTime,l=i.animationType;Nt(St(e),t,r),T3(e,s,l,function(){return Nt(St(e),t,o)}),M3(e,t)};function aq(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,o=e.transformState,i=e.contentComponent,s=o.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,h=n.doubleClick,m=h.disabled,g=h.mode,y=h.step,x=h.animationTime,_=h.animationType;if(!m&&!r){if(g==="reset")return sq(e,t);if(!i)return console.error("No ContentComponent found");var C=g==="zoomOut"?-1:1,S=k3(e,C,y);if(s!==S){Nt(St(e),t,u);var b=A3(t,i,s),E=Zx(e,S,b.x,b.y);if(!E)return console.error("Error during zoom event. New transformation state was not calculated.");Nt(St(e),t,d),Ls(e,E,x,_),M3(e,t)}}}var lq=function(e,t){var n=e.isInitialized,r=e.setup,o=e.wrapperComponent,i=r.doubleClick,s=i.disabled,l=i.excluded,u=t.target,d=o==null?void 0:o.contains(u),h=n&&u&&d&&!s;if(!h)return!1;var m=ug(u,l);return!m},cq=function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.startCoords=null,this.lastTouch=null,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.animate=!1,this.animation=null,this.maxBounds=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){dc(n,n.transformState.scale),n.setup=j2(r)},this.initializeWindowEvents=function(){var r,o=I0(),i=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,s=i==null?void 0:i.defaultView;s==null||s.addEventListener("mousedown",n.onPanningStart,o),s==null||s.addEventListener("mousemove",n.onPanning,o),s==null||s.addEventListener("mouseup",n.onPanningStop,o),i==null||i.addEventListener("mouseleave",n.clearPanning,o),s==null||s.addEventListener("keyup",n.setKeyUnPressed,o),s==null||s.addEventListener("keydown",n.setKeyPressed,o)},this.cleanupWindowEvents=function(){var r,o,i=I0(),s=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,l=s==null?void 0:s.defaultView;l==null||l.removeEventListener("mousedown",n.onPanningStart,i),l==null||l.removeEventListener("mousemove",n.onPanning,i),l==null||l.removeEventListener("mouseup",n.onPanningStop,i),s==null||s.removeEventListener("mouseleave",n.clearPanning,i),l==null||l.removeEventListener("keyup",n.setKeyUnPressed,i),l==null||l.removeEventListener("keydown",n.setKeyPressed,i),document.removeEventListener("mouseleave",n.clearPanning,i),Do(n),(o=n.observer)===null||o===void 0||o.disconnect()},this.handleInitializeWrapperEvents=function(r){var o=I0();r.addEventListener("wheel",n.onWheelZoom,o),r.addEventListener("dblclick",n.onDoubleClick,o),r.addEventListener("touchstart",n.onTouchPanningStart,o),r.addEventListener("touchmove",n.onTouchPanning,o),r.addEventListener("touchend",n.onTouchPanningStop,o)},this.handleInitialize=function(r){var o=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(i){return i(St(n))}),o&&(n.setCenter(),n.observer=new ResizeObserver(function(){var i;n.onInitCallbacks.forEach(function(s){return s(St(n))}),n.setCenter(),(i=n.observer)===null||i===void 0||i.disconnect()}),n.observer.observe(r))},this.onWheelZoom=function(r){var o=n.setup.disabled;if(!o){var i=VZ(n,r);if(i){var s=n.isPressingKeys(n.setup.wheel.activationKeys);s&&(eq(n,r),tq(n,r),nq(n,r))}}},this.onPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),Do(n),I2(n,r),Nt(St(n),r,i)))}}},this.onPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(!o){var s=N2(n);if(s){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),L2(n,r.clientX,r.clientY),Nt(St(n),r,i))}}},this.onPanningStop=function(r){var o=n.props.onPanningStop;n.isPanning&&(AZ(n),Nt(St(n),r,o))},this.onPinchStart=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinchingStart,l=i.onZoomStart;if(!o){var u=GZ(n,r);u&&(rq(n,r),Do(n),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinch=function(r){var o=n.setup.disabled,i=n.props,s=i.onPinching,l=i.onZoom;if(!o){var u=XZ(n);u&&(r.preventDefault(),r.stopPropagation(),oq(n,r),Nt(St(n),r,s),Nt(St(n),r,l))}},this.onPinchStop=function(r){var o=n.props,i=o.onPinchingStop,s=o.onZoomStop;n.pinchStartScale&&(iq(n),Nt(St(n),r,i),Nt(St(n),r,s))},this.onTouchPanningStart=function(r){var o=n.setup.disabled,i=n.props.onPanningStart;if(!o){var s=M2(n,r);if(s){var l=n.lastTouch&&+new Date-n.lastTouch<200;if(l&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,Do(n);var u=r.touches,d=u.length===1,h=u.length===2;d&&(Do(n),I2(n,r),Nt(St(n),r,i)),h&&n.onPinchStart(r)}}}},this.onTouchPanning=function(r){var o=n.setup.disabled,i=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(o)return;var s=N2(n);if(!s)return;r.preventDefault(),r.stopPropagation();var l=r.touches[0];L2(n,l.clientX,l.clientY),Nt(St(n),r,i)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var o=n.setup.disabled;if(!o){var i=lq(n,r);i&&aq(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return r.length?!!r.find(function(o){return n.pressedKeys[o]}):!0},this.setTransformState=function(r,o,i){var s=n.props.onTransformed;if(!Number.isNaN(r)&&!Number.isNaN(o)&&!Number.isNaN(i)){r!==n.transformState.scale&&(n.transformState.previousScale=n.transformState.scale,n.transformState.scale=r),n.transformState.positionX=o,n.transformState.positionY=i,n.applyTransformation();var l=St(n);n.onChangeCallbacks.forEach(function(u){return u(l)}),Nt(l,{scale:r,positionX:o,positionY:i},s)}else console.error("Detected NaN set state values")},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=P3(n.transformState.scale,n.wrapperComponent,n.contentComponent);n.setTransformState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,o,i){return n.props.customTransform?n.props.customTransform(r,o,i):BZ(r,o,i)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.transformState,o=r.scale,i=r.positionX,s=r.positionY,l=n.handleTransformStyles(i,s,o);n.contentComponent.style.transform=l}},this.getContext=function(){return St(n)},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,o){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=o,dc(n,n.transformState.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(o),n.initializeWindowEvents(),n.isInitialized=!0;var i=St(n);Nt(i,void 0,n.props.onInit)},this.props=t,this.setup=j2(this.props),this.transformState=$3(this.props)}return e}(),qx=Fe.createContext(null),uq=function(e,t){return typeof e=="function"?e(t):e},dq=Fe.forwardRef(function(e,t){var n=f.useRef(new cq(e)).current,r=uq(e.children,F1(n));return f.useImperativeHandle(t,function(){return F1(n)},[n]),f.useEffect(function(){n.update(e)},[n,e]),Fe.createElement(qx.Provider,{value:n},r)});Fe.forwardRef(function(e,t){var n=f.useRef(null),r=f.useContext(qx);return f.useEffect(function(){return r.onChange(function(o){if(n.current){var i=0,s=0;n.current.style.transform=r.handleTransformStyles(i,s,1/o.instance.transformState.scale)}})},[r]),Fe.createElement("div",_s({},e,{ref:UZ([n,t])}))});function fq(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(!e||typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",n==="top"&&r.firstChild?r.insertBefore(o,r.firstChild):r.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var pq=`.transform-component-module_wrapper__SPB86 { + position: relative; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + overflow: hidden; + -webkit-touch-callout: none; /* iOS Safari */ + -webkit-user-select: none; /* Safari */ + -khtml-user-select: none; /* Konqueror HTML */ + -moz-user-select: none; /* Firefox */ + -ms-user-select: none; /* Internet Explorer/Edge */ + user-select: none; + margin: 0; + padding: 0; +} +.transform-component-module_content__FBWxo { + display: flex; + flex-wrap: wrap; + width: -moz-fit-content; + width: fit-content; + height: -moz-fit-content; + height: fit-content; + margin: 0; + padding: 0; + transform-origin: 0% 0%; +} +.transform-component-module_content__FBWxo img { + pointer-events: none; +} +`,z2={wrapper:"transform-component-module_wrapper__SPB86",content:"transform-component-module_content__FBWxo"};fq(pq);var hq=function(e){var t=e.children,n=e.wrapperClass,r=n===void 0?"":n,o=e.contentClass,i=o===void 0?"":o,s=e.wrapperStyle,l=e.contentStyle,u=e.wrapperProps,d=u===void 0?{}:u,h=e.contentProps,m=h===void 0?{}:h,g=f.useContext(qx),y=g.init,x=g.cleanupWindowEvents,_=f.useRef(null),C=f.useRef(null);return f.useEffect(function(){var S=_.current,b=C.current;return S!==null&&b!==null&&y&&(y==null||y(S,b)),function(){x==null||x()}},[]),Fe.createElement("div",_s({},d,{ref:_,className:"react-transform-wrapper ".concat(z2.wrapper," ").concat(r),style:s}),Fe.createElement("div",_s({},m,{ref:C,className:"react-transform-component ".concat(z2.content," ").concat(i),style:l}),t))};const N3=["PageUp","PageDown"],D3=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],I3={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},Wd="Slider",[z1,mq,gq]=zd(Wd),[L3,Ete]=An(Wd,[gq]),[vq,dg]=L3(Wd),yq=f.forwardRef((e,t)=>{const{name:n,min:r=0,max:o=100,step:i=1,orientation:s="horizontal",disabled:l=!1,minStepsBetweenThumbs:u=0,defaultValue:d=[r],value:h,onValueChange:m=()=>{},onValueCommit:g=()=>{},inverted:y=!1,...x}=e,[_,C]=f.useState(null),S=Be(t,U=>C(U)),b=f.useRef(new Set),E=f.useRef(0),k=s==="horizontal",P=_?!!_.closest("form"):!0,M=k?wq:xq,[A=[],O]=Zr({prop:h,defaultProp:d,onChange:U=>{var te;(te=[...b.current][E.current])===null||te===void 0||te.focus(),m(U)}}),F=f.useRef(A);function V(U){const te=Tq(A,U);ae(U,te)}function J(U){ae(U,E.current)}function G(){const U=F.current[E.current];A[E.current]!==U&&g(A)}function ae(U,te,{commit:L}={commit:!1}){const ie=Mq(i),K=Nq(Math.round((U-r)/i)*i+r,ie),Q=id(K,[r,o]);O((W=[])=>{const le=kq(W,Q,te);if(Oq(le,u*i)){E.current=le.indexOf(Q);const ge=String(le)!==String(W);return ge&&L&&g(le),ge?le:W}else return W})}return f.createElement(vq,{scope:e.__scopeSlider,disabled:l,min:r,max:o,valueIndexToChangeRef:E,thumbs:b.current,values:A,orientation:s},f.createElement(z1.Provider,{scope:e.__scopeSlider},f.createElement(z1.Slot,{scope:e.__scopeSlider},f.createElement(M,Y({"aria-disabled":l,"data-disabled":l?"":void 0},x,{ref:S,onPointerDown:ue(x.onPointerDown,()=>{l||(F.current=A)}),min:r,max:o,inverted:y,onSlideStart:l?void 0:V,onSlideMove:l?void 0:J,onSlideEnd:l?void 0:G,onHomeKeyDown:()=>!l&&ae(r,0,{commit:!0}),onEndKeyDown:()=>!l&&ae(o,A.length-1,{commit:!0}),onStepKeyDown:({event:U,direction:te})=>{if(!l){const K=N3.includes(U.key)||U.shiftKey&&D3.includes(U.key)?10:1,Q=E.current,W=A[Q],le=i*K*te;ae(W+le,Q,{commit:!0})}}})))),P&&A.map((U,te)=>f.createElement($q,{key:te,name:n?n+(A.length>1?"[]":""):void 0,value:U})))}),[F3,j3]=L3(Wd,{startEdge:"left",endEdge:"right",size:"width",direction:1}),wq=f.forwardRef((e,t)=>{const{min:n,max:r,dir:o,inverted:i,onSlideStart:s,onSlideMove:l,onSlideEnd:u,onStepKeyDown:d,...h}=e,[m,g]=f.useState(null),y=Be(t,E=>g(E)),x=f.useRef(),_=Sc(o),C=_==="ltr",S=C&&!i||!C&&i;function b(E){const k=x.current||m.getBoundingClientRect(),P=[0,k.width],A=Qx(P,S?[n,r]:[r,n]);return x.current=k,A(E-k.left)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:S?"left":"right",endEdge:S?"right":"left",direction:S?1:-1,size:"width"},f.createElement(z3,Y({dir:_,"data-orientation":"horizontal"},h,{ref:y,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:E=>{const k=b(E.clientX);s==null||s(k)},onSlideMove:E=>{const k=b(E.clientX);l==null||l(k)},onSlideEnd:()=>{x.current=void 0,u==null||u()},onStepKeyDown:E=>{const P=I3[S?"from-left":"from-right"].includes(E.key);d==null||d({event:E,direction:P?-1:1})}})))}),xq=f.forwardRef((e,t)=>{const{min:n,max:r,inverted:o,onSlideStart:i,onSlideMove:s,onSlideEnd:l,onStepKeyDown:u,...d}=e,h=f.useRef(null),m=Be(t,h),g=f.useRef(),y=!o;function x(_){const C=g.current||h.current.getBoundingClientRect(),S=[0,C.height],E=Qx(S,y?[r,n]:[n,r]);return g.current=C,E(_-C.top)}return f.createElement(F3,{scope:e.__scopeSlider,startEdge:y?"bottom":"top",endEdge:y?"top":"bottom",size:"height",direction:y?1:-1},f.createElement(z3,Y({"data-orientation":"vertical"},d,{ref:m,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const C=x(_.clientY);i==null||i(C)},onSlideMove:_=>{const C=x(_.clientY);s==null||s(C)},onSlideEnd:()=>{g.current=void 0,l==null||l()},onStepKeyDown:_=>{const S=I3[y?"from-bottom":"from-top"].includes(_.key);u==null||u({event:_,direction:S?-1:1})}})))}),z3=f.forwardRef((e,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:o,onSlideEnd:i,onHomeKeyDown:s,onEndKeyDown:l,onStepKeyDown:u,...d}=e,h=dg(Wd,n);return f.createElement(Pe.span,Y({},d,{ref:t,onKeyDown:ue(e.onKeyDown,m=>{m.key==="Home"?(s(m),m.preventDefault()):m.key==="End"?(l(m),m.preventDefault()):N3.concat(D3).includes(m.key)&&(u(m),m.preventDefault())}),onPointerDown:ue(e.onPointerDown,m=>{const g=m.target;g.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(g)?g.focus():r(m)}),onPointerMove:ue(e.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&o(m)}),onPointerUp:ue(e.onPointerUp,m=>{const g=m.target;g.hasPointerCapture(m.pointerId)&&(g.releasePointerCapture(m.pointerId),i(m))})}))}),bq="SliderTrack",_q=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(bq,n);return f.createElement(Pe.span,Y({"data-disabled":o.disabled?"":void 0,"data-orientation":o.orientation},r,{ref:t}))}),B2="SliderRange",Sq=f.forwardRef((e,t)=>{const{__scopeSlider:n,...r}=e,o=dg(B2,n),i=j3(B2,n),s=f.useRef(null),l=Be(t,s),u=o.values.length,d=o.values.map(g=>B3(g,o.min,o.max)),h=u>1?Math.min(...d):0,m=100-Math.max(...d);return f.createElement(Pe.span,Y({"data-orientation":o.orientation,"data-disabled":o.disabled?"":void 0},r,{ref:l,style:{...e.style,[i.startEdge]:h+"%",[i.endEdge]:m+"%"}}))}),U2="SliderThumb",Eq=f.forwardRef((e,t)=>{const n=mq(e.__scopeSlider),[r,o]=f.useState(null),i=Be(t,l=>o(l)),s=f.useMemo(()=>r?n().findIndex(l=>l.ref.current===r):-1,[n,r]);return f.createElement(Cq,Y({},e,{ref:i,index:s}))}),Cq=f.forwardRef((e,t)=>{const{__scopeSlider:n,index:r,...o}=e,i=dg(U2,n),s=j3(U2,n),[l,u]=f.useState(null),d=Be(t,C=>u(C)),h=gx(l),m=i.values[r],g=m===void 0?0:B3(m,i.min,i.max),y=Rq(r,i.values.length),x=h==null?void 0:h[s.size],_=x?Pq(x,g,s.direction):0;return f.useEffect(()=>{if(l)return i.thumbs.add(l),()=>{i.thumbs.delete(l)}},[l,i.thumbs]),f.createElement("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[s.startEdge]:`calc(${g}% + ${_}px)`}},f.createElement(z1.ItemSlot,{scope:e.__scopeSlider},f.createElement(Pe.span,Y({role:"slider","aria-label":e["aria-label"]||y,"aria-valuemin":i.min,"aria-valuenow":m,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0},o,{ref:d,style:m===void 0?{display:"none"}:e.style,onFocus:ue(e.onFocus,()=>{i.valueIndexToChangeRef.current=r})}))))}),$q=e=>{const{value:t,...n}=e,r=f.useRef(null),o=Fx(t);return f.useEffect(()=>{const i=r.current,s=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(s,"value").set;if(o!==t&&u){const d=new Event("input",{bubbles:!0});u.call(i,t),i.dispatchEvent(d)}},[o,t]),f.createElement("input",Y({style:{display:"none"}},n,{ref:r,defaultValue:t}))};function kq(e=[],t,n){const r=[...e];return r[n]=t,r.sort((o,i)=>o-i)}function B3(e,t,n){const i=100/(n-t)*(e-t);return id(i,[0,100])}function Rq(e,t){return t>2?`Value ${e+1} of ${t}`:t===2?["Minimum","Maximum"][e]:void 0}function Tq(e,t){if(e.length===1)return 0;const n=e.map(o=>Math.abs(o-t)),r=Math.min(...n);return n.indexOf(r)}function Pq(e,t,n){const r=e/2,i=Qx([0,50],[0,r]);return(r-i(t)*n)*n}function Aq(e){return e.slice(0,-1).map((t,n)=>e[n+1]-t)}function Oq(e,t){if(t>0){const n=Aq(e);return Math.min(...n)>=t}return!0}function Qx(e,t){return n=>{if(e[0]===e[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(e[1]-e[0]);return t[0]+r*(n-e[0])}}function Mq(e){return(String(e).split(".")[1]||"").length}function Nq(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}const U3=yq,Dq=_q,Iq=Sq,Lq=Eq,uo=f.forwardRef(({className:e,...t},n)=>v.jsxs(U3,{ref:n,className:Ce("relative flex w-full touch-none select-none items-center",e),tabIndex:-1,...t,children:[v.jsx(Dq,{className:"relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20 data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",children:v.jsx(Iq,{className:"absolute h-full bg-primary data-[disabled]:cursor-not-allowed "})}),v.jsx(Lq,{tabIndex:-1,className:"block h-4 w-4 rounded-full border border-primary/60 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring data-[disabled]:cursor-not-allowed"})]}));uo.displayName=U3.displayName;const tl={capture:!0,passive:!1},Fq=2,V2=(e,t,n,r,o,i)=>{if(e!==n&&t===r){if(e<0)return[0,r];if(e+t>i)return[i-r,r]}else{if(ti)return[e,i-e]}return[e,t]},jq=e=>{const{minHeight:t,minWidth:n,maxHeight:r,maxWidth:o,scale:i,show:s}=e,[l,u,d,h,{x:m,y:g,width:y,height:x},_,C,S,b,E,k]=bt(W=>[W.imageWidth,W.imageHeight,W.isInpainting,W.isSD(),W.cropperState,W.setCropperX,W.setCropperY,W.setCropperWidth,W.setCropperHeight,W.isCropperExtenderResizing,W.setIsCropperExtenderResizing]),[P,M]=f.useState(!1);f.useEffect(()=>{_(Math.round((o-512)/2)),C(Math.round((r-512)/2))},[r,o,l,u]);const[A,O]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),F=()=>{},V=(W,le)=>V2(W,le,m,y,n,o),J=(W,le)=>V2(W,le,g,x,t,r),G=W=>{if(d)return;const le=W.clientX,ge=W.clientY,Ve=Math.round((ge-A.startResizeY)/i),Ue=Math.round((le-A.startResizeX)/i),We=()=>{const $e=A.initHeight-Ve,Ae=A.initY+Ve,[Oe,je]=J(Ae,$e);b(je),C(Oe)},Me=()=>{const $e=A.initHeight+Ve,[Ae,Oe]=J(A.initY,$e);b(Oe),C(Ae)},fe=()=>{const $e=A.initWidth-Ue,Ae=A.initX+Ue,[Oe,je]=V(Ae,$e);S(je),_(Oe)},xe=()=>{const $e=A.initWidth+Ue,[Ae,Oe]=V(A.initX,$e);S(Oe),_(Ae)};if(E)switch(A.ord){case"topleft":{We(),fe();break}case"topright":{We(),xe();break}case"bottomleft":{Me(),fe();break}case"bottomright":{Me(),xe();break}case"top":{We();break}case"right":{xe();break}case"bottom":{Me();break}case"left":{fe();break}}if(P){const $e=A.initX+Ue,Ae=A.initY+Ve,[Oe,je]=V($e,A.initWidth),[Ot,ct]=J(Ae,A.initHeight);S(je),b(ct),_(Oe),C(Ot)}},ae=()=>{E&&k(!1),P&&M(!1)};f.useEffect(()=>{if(E||P)return document.addEventListener("pointermove",G,tl),document.addEventListener("pointerup",ae,tl),document.addEventListener("pointercancel",ae,tl),()=>{document.removeEventListener("pointermove",G,tl),document.removeEventListener("pointerup",ae,tl),document.removeEventListener("pointercancel",ae,tl)}},[E,P,y,x,A]);const U=W=>{const{ord:le}=W.target.dataset;le&&(k(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:le}))},te=(W,le,ge)=>{const We="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Me="0",fe="0",xe=ge,$e="-6px";return ge===""&&($e="50%",le==="left"||le==="right"?(xe="top",fe="-50%"):(xe="left",Me="-50%")),v.jsx("div",{className:Ce(We,W),style:{[le]:-6,[xe]:$e,transform:`translate(${Me}, ${fe}) scale(${1/i})`},"data-ord":le+ge,"aria-label":le+ge,tabIndex:-1,role:"button"})},L=()=>v.jsxs("div",{onFocus:F,onPointerDown:U,className:"absolute top-0 h-full w-full",children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),te("cursor-nw-resize","top","left"),te("cursor-ne-resize","top","right"),te("cursor-sw-resize","bottom","left"),te("cursor-se-resize","bottom","right"),te("cursor-ns-resize","top",""),te("cursor-ns-resize","bottom",""),te("cursor-ew-resize","left",""),te("cursor-ew-resize","right","")]}),ie=W=>{M(!0),O({initX:m,initY:g,initHeight:x,initWidth:y,startResizeX:W.clientX,startResizeY:W.clientY,ord:""})},K=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full hover:cursor-move bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/i*.8})`},onPointerDown:ie,children:[y," x ",x]}),Q=()=>v.jsx("div",{className:"outline-dashed outline-primary",style:{height:x,width:y,outlineWidth:`${Fq/i*1.3}px`}});return s===!1||!h?null:v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:x,width:y,left:m,top:g},children:[Q(),K(),L()]})})},zq=()=>{const[e,t,n]=bt(r=>[r.interactiveSegState,r.resetInteractiveSegState,r.handleInteractiveSegAccept]);return e.isInteractiveSeg?v.jsxs("div",{className:"z-10 absolute top-[68px] rounded-xl border-solid border p-[8px] left-1/2 translate-x-[-50%] flex justify-center items-center gap-[8px] bg-background",children:[v.jsx(yn,{onClick:()=>{t()},size:"sm",variant:"secondary",children:"Cancel"}),v.jsx(yn,{size:"sm",onClick:()=>{n()},children:"Accept"})]}):null},Bq=e=>{const{x:t,y:n,positive:r}=e,o=r?"bg-[rgba(21,_215,_121,_0.936)] outline-[rgba(98,255,179,0.31)]":"bg-[rgba(237,_49,_55,_0.942)] outline-[rgba(255,89,95,0.31)]";return v.jsx("div",{className:`absolute h-[10px] w-[10px] rounded-[50%] ${o} outline-8 outline`,style:{left:t,top:n,transform:"translate(-50%, -50%)"}})},Uq=()=>{const e=bt(t=>t.interactiveSegState.clicks);return v.jsx("div",{className:"absolute h-full w-full overflow-hidden pointer-events-none",children:e.map(t=>v.jsx(Bq,{x:t[0],y:t[1],positive:t[2]===1},t[3]))})},Vq=()=>v.jsx("div",{children:v.jsx(zq,{})}),nl={capture:!0,passive:!1},Wq=2,W2=(e,t,n,r)=>t{const{minHeight:t,minWidth:n,scale:r,show:o}=e,[i,s,l,u,{x:d,y:h,width:m,height:g},y,x,_,C,S,b,E]=bt(ie=>[ie.isInpainting,ie.imageHeight,ie.imageWidth,ie.isSD(),ie.extenderState,ie.setExtenderX,ie.setExtenderY,ie.setExtenderWidth,ie.setExtenderHeight,ie.settings.extenderDirection,ie.isCropperExtenderResizing,ie.setIsCropperExtenderResizing]),[k,P]=f.useState({initX:0,initY:0,initHeight:0,initWidth:0,startResizeX:0,startResizeY:0,ord:"top"}),M=()=>{},A=(ie,K)=>W2(ie,K,d,n),O=(ie,K)=>W2(ie,K,h,t),F=ie=>{if(i)return;const K=ie.clientX,Q=ie.clientY,W=Math.round((Q-k.startResizeY)/r),le=Math.round((K-k.startResizeX)/r),ge=()=>{const Me=k.initHeight-W,fe=k.initY+W;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initHeight-Math.abs(k.initY));else{const Ae=O(fe,Me);xe=Ae[0],$e=Ae[1]}C($e),x(xe)},Ve=()=>{const Me=k.initHeight+W;let[fe,xe]=O(k.initY,Me);S===In.xy&&xe{const Me=k.initWidth-le,fe=k.initX+le;let xe=fe,$e=Me;if(S===In.xy)xe>0&&(xe=0,$e=k.initWidth-Math.abs(k.initX));else{const Ae=A(fe,Me);xe=Ae[0],$e=Ae[1]}_($e),y(xe)},We=()=>{const Me=k.initWidth+le;let[fe,xe]=A(k.initX,Me);S===In.xy&&xe{b&&E(!1)};f.useEffect(()=>{if(b)return document.addEventListener("pointermove",F,nl),document.addEventListener("pointerup",V,nl),document.addEventListener("pointercancel",V,nl),()=>{document.removeEventListener("pointermove",F,nl),document.removeEventListener("pointerup",V,nl),document.removeEventListener("pointercancel",V,nl)}},[b,m,g,k]);const J=ie=>{const{ord:K}=ie.target.dataset;K&&(E(!0),P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:K}))},G=(ie,K,Q)=>{const ge="w-[12px] h-[12px] z-[4] absolute content-[''] block border-2 border-primary borde pointer-events-auto hover:bg-primary";let Ve="0",Ue="0",We=Q,Me="-6px";return Q===""&&(Me="50%",K==="left"||K==="right"?(We="top",Ue="-50%"):(We="left",Ve="-50%")),v.jsx("div",{className:Ce(ge,ie),style:{[K]:-6,[We]:Me,transform:`translate(${Ve}, ${Ue}) scale(${1/r})`},"data-ord":K+Q,"aria-label":K+Q,tabIndex:-1,role:"button"})},ae=()=>v.jsxs("div",{onFocus:M,onPointerDown:J,className:"absolute top-0 h-full w-full",children:[[In.y,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 w-full cursor-ns-resize h-[12px] mt-[-6px]","data-ord":"top"}),v.jsx("div",{className:"absolute pointer-events-auto bottom-0 left-0 w-full cursor-ns-resize h-[12px] mb-[-6px]","data-ord":"bottom"}),G("cursor-ns-resize","top",""),G("cursor-ns-resize","bottom","")]}):v.jsx(v.Fragment,{}),[In.x,In.xy].includes(S)?v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"absolute pointer-events-auto top-0 right-0 h-full cursor-ew-resize w-[12px] mr-[-6px]","data-ord":"right"}),v.jsx("div",{className:"absolute pointer-events-auto top-0 left-0 h-full cursor-ew-resize w-[12px] ml-[-6px]","data-ord":"left"}),G("cursor-ew-resize","left",""),G("cursor-ew-resize","right","")]}):v.jsx(v.Fragment,{}),S===In.xy?v.jsxs(v.Fragment,{children:[G("cursor-nw-resize","top","left"),G("cursor-ne-resize","top","right"),G("cursor-sw-resize","bottom","left"),G("cursor-se-resize","bottom","right")]}):v.jsx(v.Fragment,{})]}),U=ie=>{P({initX:d,initY:h,initHeight:g,initWidth:m,startResizeX:ie.clientX,startResizeY:ie.clientY,ord:""})},te=()=>v.jsxs("div",{className:Jw("border absolute pointer-events-auto px-2 py-1 rounded-full bg-background","origin-top-left top-0 left-0"),style:{transform:`scale(${1/r*.8})`},onPointerDown:U,children:[m," x ",g]}),L=()=>v.jsx("div",{className:Ce("outline-dashed outline-primary"),style:{height:g,width:m,outlineWidth:`${Wq/r*1.3}px`}});return o===!1||!u?null:v.jsx("div",{className:"absolute h-full w-full pointer-events-none z-[2]",children:v.jsxs("div",{className:"relative pointer-events-none z-[2] [box-shadow:0_0_0_9999px_rgba(0,_0,_0,_0.5)]",style:{height:g,width:m,left:d,top:h},children:[L(),te(),ae()]})})},Kq=200,Yq=10,Gq=200,lu=300;function Xq(e){const{file:t}=e,{toast:n}=Td(),[r,o,i,s,l,u,d,h,m,g,y,x,_,C,S,b,E,k,P,M,A,O]=bt(H=>[H.disableShortCuts,H.windowSize,H.isInpainting,H.imageWidth,H.imageHeight,H.settings,H.serverConfig.enableAutoSaving,H.setImageSize,H.setBaseBrushSize,H.interactiveSegState,H.updateInteractiveSegState,H.handleCanvasMouseDown,H.handleCanvasMouseMove,H.undo,H.redo,H.undoDisabled(),H.redoDisabled(),H.getIsProcessing(),H.updateAppState,H.runMannually(),H.runInpainting,H.isCropperExtenderResizing]),F=bt(H=>H.editorState.baseBrushSize),V=bt(H=>H.getBrushSize()),J=bt(H=>H.editorState.renders),G=bt(H=>H.editorState.extraMasks),ae=bt(H=>H.editorState.temporaryMasks),U=bt(H=>H.editorState.lineGroups),te=bt(H=>H.editorState.curLineGroup),[L,ie]=f.useState(!1),[K,Q]=Rx(t),[W,le]=f.useState(),[ge,Ve]=f.useState(),[{x:Ue,y:We},Me]=f.useState({x:-1,y:-1}),[fe,xe]=f.useState(!1),[$e,Ae]=f.useState(!1),[Oe,je]=f.useState(!1),[Ot,ct]=f.useState(1),[Kt,Er]=f.useState(!1),[gt,js]=f.useState(1),I=o.width/2,X=o.height/2,Z=f.useRef(null),[we,he]=f.useState(!1),[de,ke]=f.useState(!1),[ft,pt]=f.useState(0),_n=f.useCallback(()=>te.length!==0,[te]);f.useEffect(()=>{if(!ge||!Q||s===0||l===0)return;const H=J.length===0?K:J[J.length-1];ge.canvas.width=s,ge.canvas.height=l,ge.clearRect(0,0,ge.canvas.width,ge.canvas.height),ge.drawImage(H,0,0,s,l)},[J,K,Q,ge,l,s]),f.useEffect(()=>{!W||!Q||s===0||l===0||(W.canvas.width=s,W.canvas.height=l,W.clearRect(0,0,W.canvas.width,W.canvas.height),ae.forEach(H=>{W.drawImage(H,0,0,s,l)}),G.forEach(H=>{W.drawImage(H,0,0,s,l)}),g.isInteractiveSeg&&g.tmpInteractiveSegMask&&W.drawImage(g.tmpInteractiveSegMask,0,0,s,l),GR(W,te))},[ae,G,Q,g,W,te,l,s]);const Cr=f.useCallback(async()=>{let H=t;if(J.length>0){const Ge=J[J.length-1];H=await ku(Ge.currentSrc,t.name,t.type)}return H},[t,J]),ki=()=>J.length!==0,_o=f.useCallback(()=>{let H=512,Ge=512;return Q?(J.length===0?(H=K.naturalWidth,Ge=K.naturalHeight):J.length!==0&&(H=J[J.length-1].width,Ge=J[J.length-1].height),[H,Ge]):[H,Ge]},[K,Q,J]);f.useEffect(()=>{var Gd;if(!Q)return;const[H,Ge]=_o();(H!==s||Ge!==l)&&h(H,Ge);const st=o.width/H,Qr=(o.height-Kq)/Ge;let an=1;(st<1||Qr<1)&&(an=Math.min(st,Qr)),js(an),ct(an),console.log(`[on file load] image size: ${H}x${Ge}, scale: ${an}, initialCentered: ${we}`),W!=null&&W.canvas&&(console.log("[on file load] set canvas size"),H!=W.canvas.width&&(W.canvas.width=H),Ge!=W.canvas.height&&(W.canvas.height=Ge)),we||((Gd=Z.current)==null||Gd.centerView(an,1),console.log("[on file load] centerView"),he(!0))},[Z,l,s,K,Q,o,we,_o]),f.useEffect(()=>{var H;console.log("[useEffect] centerView"),(H=Z==null?void 0:Z.current)==null||H.centerView(gt,1)},[l,s,Z,gt]);const Vn=f.useCallback(()=>{if(!gt||!o)return;const H=Z.current;if(!H)return;const Ge=(o.width-s*gt)/2,st=(o.height-l*gt)/2;H.setTransform(Ge,st,gt,200,"easeOutQuad"),H.instance.transformState.scale&&(H.instance.transformState.scale=gt),ct(gt),Er(!1)},[Z,o,l,s,o.height,gt]);f.useEffect(()=>(window.addEventListener("resize",()=>{Vn()}),()=>{window.removeEventListener("resize",()=>{Vn()})}),[o,Vn]),Zn("Escape",()=>{k||(de?ke(!1):Vn())},[de,i,Vn]);const Ri=H=>{const Ge=H.nativeEvent;Me({x:Ge.pageX,y:Ge.pageY})},zs=H=>{k||g.isInteractiveSeg||Oe||de&&te.length!==0&&_(c0(H))},Ti=async H=>{P({isPluginRunning:!0});const Ge=await Cr();try{const st=await gT(!0,jR.InteractiveSeg,Ge,void 0,H),{blob:Qr}=st,an=new Image;an.onload=()=>{y({tmpInteractiveSegMask:an})},an.src=Qr}catch(st){n({variant:"destructive",description:st.message?st.message:st.toString()})}P({isPluginRunning:!1})},$c=H=>{if(!_n())return;if(cC(H)){je(!1);return}g.isInteractiveSeg||Oe||!K.src||!(W!=null&&W.canvas)||i||de&&(M?ke(!1):A())},yg=H=>{if(g.isInteractiveSeg){const Ge=c0(H),st=[...g.clicks];lC(H)?st.push([Ge.x,Ge.y,0,st.length]):st.push([Ge.x,Ge.y,1,st.length]),Ti(st),y({clicks:st})}},wg=H=>{if(!(k||g.isInteractiveSeg||Oe||!Q||!(W!=null&&W.canvas))&&!lC(H)){if(cC(H)){je(!0);return}ke(!0),x(c0(H))}},Kd=H=>{H.preventDefault(),C()};Zn("meta+z,ctrl+z",Kd);const kc=H=>{H.preventDefault(),S()};Zn("shift+ctrl+z,shift+meta+z",kc),o2("Tab",H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},H=>{H==null||H.preventDefault(),H==null||H.stopPropagation(),ki()&&(window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu))});const Rc=f.useCallback(async()=>{if(t===void 0)return;if(d&&J.length>0){try{await Wj(J[J.length-1],t.name,t.type),n({description:"Save image success"})}catch(st){n({variant:"destructive",title:"Uh oh! Something went wrong.",description:st.message?st.message:st.toString()})}return}const H=t.name.replace(/(\.[\w\d_-]+)$/i,"_cleanup$1"),Ge=J[J.length-1];if(yF(Ge.currentSrc,H),u.enableDownloadMask){let st=t.name.replace(/(\.[\w\d_-]+)$/i,"_mask$1");st=st.replace(/\.[^/.]+$/,".jpg");const Qr=Lp(s,l,U),an=document.createElement("a");an.download=st,an.href=Qr.toDataURL("image/jpeg"),an.click()}},[t,d,J,u,l,s,U]);Zn("meta+s,ctrl+s",Rc);const Tc=H=>{H!==fe&&!Oe&&!O&&xe(H)},xg=f.useCallback(()=>{if(k)return"default";if(Oe)return"grab";if(fe)return"none"},[fe,Oe,k]);Zn("[",()=>{let H=F;F>10&&(H=F-10),F<=10&&F>0&&(H=F-5),m(H)},[F]),Zn("]",()=>{m(F+10)},[F]),Zn("shift+r",()=>{M&&_n()&&A()},[M,A,_n]),Zn("ctrl+c,meta+c",async()=>{await hF()&&J.length>0&&W!=null&&W.canvas&&(await vF(W==null?void 0:W.canvas),n({title:"Copy inpainting result to clipboard"}))},[J,W]),o2(" ",H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!1),je(!0))},H=>{r||(H==null||H.preventDefault(),H==null||H.stopPropagation(),xe(!0),je(!1))});const Pc=()=>{var Ge,st,Qr,an;let H=gt;return((st=(Ge=Z.current)==null?void 0:Ge.instance)==null?void 0:st.transformState.scale)!==void 0&&(H=(an=(Qr=Z.current)==null?void 0:Qr.instance)==null?void 0:an.transformState.scale),H},Yd=(H,Ge)=>{const st=Pc();return{width:`${V*st}px`,height:`${V*st}px`,left:`${H}px`,top:`${Ge}px`,transform:"translate(-50%, -50%)"}},Ac=H=>v.jsx("div",{className:"absolute rounded-[50%] border-[1px] border-[solid] border-[#ffcc00] pointer-events-none bg-[#ffcc00bb]",style:H}),bg=H=>{m(H),$e||(Ae(!0),window.setTimeout(()=>{Ae(!1)},1e4))},_g=()=>v.jsx("div",{className:"absolute h-[20px] w-[20px] pointer-events-none rounded-[50%] bg-[rgba(21,_215,_121,_0.936)] [box-shadow:0_0_0_0_rgba(21,_215,_121,_0.936)] animate-pulse",style:{left:`${Ue}px`,top:`${We}px`,transform:"translate(-50%, -50%)"},children:v.jsx(uK,{})}),Sg=()=>v.jsx(dq,{ref:H=>{H&&(Z.current=H)},panning:{disabled:!Oe,velocityDisabled:!0},wheel:{step:.05},centerZoomedOut:!0,alignmentAnimation:{disabled:!0},centerOnInit:!0,limitToBounds:!1,doubleClick:{disabled:!0},initialScale:gt,minScale:gt*.3,onPanning:()=>{Kt||Er(!0)},onZoom:H=>{ct(H.state.scale)},children:v.jsxs(hq,{contentStyle:{visibility:we?"visible":"hidden"},children:[v.jsxs("div",{className:"grid [grid-template-areas:'editor-content'] gap-y-4",children:[v.jsx("canvas",{className:"[grid-area:editor-content]",style:{clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},ref:H=>{if(H&&!ge){const Ge=H.getContext("2d");Ge&&Ve(Ge)}}}),v.jsx("canvas",{className:Ce("[grid-area:editor-content]",k?"pointer-events-none animate-pulse duration-600":""),style:{cursor:xg(),clipPath:`inset(0 ${ft}% 0 0)`,transition:`clip-path ${lu}ms`},onContextMenu:H=>{H.preventDefault()},onMouseOver:()=>{Tc(!0),Ae(!1)},onFocus:()=>Tc(!0),onMouseLeave:()=>Tc(!1),onMouseDown:wg,onMouseUp:yg,onMouseMove:zs,ref:H=>{if(H&&!W){const Ge=H.getContext("2d");Ge&&le(Ge)}}}),v.jsx("div",{className:"[grid-area:editor-content] pointer-events-none grid [grid-template-areas:'original-image-content']",style:{width:`${s}px`,height:`${l}px`},children:L&&v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"[grid-area:original-image-content] z-10 bg-primary h-full w-[6px] justify-self-end",style:{marginRight:`${ft}%`,transition:`margin-right ${lu}ms`}}),v.jsx("img",{className:"[grid-area:original-image-content]",src:K.src,alt:"original",style:{width:`${s}px`,height:`${l}px`}})]})})]}),v.jsx(jq,{maxHeight:l,maxWidth:s,minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showCropper}),v.jsx(Hq,{minHeight:Math.min(512,l),minWidth:Math.min(512,s),scale:Pc(),show:u.showExtender}),g.isInteractiveSeg?v.jsx(Uq,{}):v.jsx(v.Fragment,{})]})});return v.jsxs("div",{className:"flex w-screen h-screen justify-center items-center","aria-hidden":"true",onMouseMove:Ri,onMouseUp:$c,children:[Sg(),fe&&!i&&!Oe&&(g.isInteractiveSeg?_g():Ac(Yd(Ue,We))),$e&&Ac(Yd(I,X)),v.jsxs("div",{className:" overflow-hidden fixed flex bottom-5 border px-4 py-2 rounded-[3rem] gap-8 items-center justify-center backdrop-filter backdrop-blur-md bg-background/70",children:[v.jsx(uo,{className:"w-48",defaultValue:[50],min:Yq,max:Gq,step:1,tabIndex:-1,value:[F],onValueChange:H=>bg(H[0]),onClick:()=>Ae(!1)}),v.jsxs("div",{className:"flex gap-2",children:[v.jsx(vn,{tooltip:"Reset zoom & pan",disabled:Ot===gt&&Kt===!1,onClick:Vn,children:v.jsx(qU,{})}),v.jsx(vn,{tooltip:"Undo",onClick:Kd,disabled:b,children:v.jsx(sV,{})}),v.jsx(vn,{tooltip:"Redo",onClick:kc,disabled:E,children:v.jsx(rV,{})}),v.jsx(vn,{tooltip:"Show original image",onPointerDown:H=>{H.preventDefault(),ie(()=>(window.setTimeout(()=>{pt(100)},10),!0))},onPointerUp:()=>{window.setTimeout(()=>{pt(0)},10),window.setTimeout(()=>{ie(!1)},lu)},disabled:J.length===0,children:v.jsx(QU,{})}),v.jsx(vn,{tooltip:"Save Image",disabled:!J.length,onClick:Rc,children:v.jsx(XU,{})}),u.enableManualInpainting&&u.model.model_type==="inpaint"?v.jsx(vn,{tooltip:"Run Inpainting",disabled:k||!_n()&&G.length===0,onClick:()=>{A()},children:v.jsx(ZU,{})}):v.jsx(v.Fragment,{})]})]})]})}const Zq=()=>{const[e,t]=bt(n=>[n.imageWidth,n.imageHeight]);return!e||!t?null:v.jsxs("div",{className:"border rounded-lg px-2 py-[6px] z-10 bg-background",children:[e,"x",t]})},B1=["Enter"," "],qq=["ArrowDown","PageUp","Home"],V3=["ArrowUp","PageDown","End"],Qq=[...qq,...V3],Jq={ltr:[...B1,"ArrowRight"],rtl:[...B1,"ArrowLeft"]},eQ={ltr:["ArrowLeft"],rtl:["ArrowRight"]},fg="Menu",[ld,tQ,nQ]=zd(fg),[Na,W3]=An(fg,[nQ,Ns,Qm]),pg=Ns(),H3=Qm(),[K3,Fs]=Na(fg),[rQ,Hd]=Na(fg),oQ=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:o,onOpenChange:i,modal:s=!0}=e,l=pg(t),[u,d]=f.useState(null),h=f.useRef(!1),m=Ft(i),g=Sc(o);return f.useEffect(()=>{const y=()=>{h.current=!0,document.addEventListener("pointerdown",x,{capture:!0,once:!0}),document.addEventListener("pointermove",x,{capture:!0,once:!0})},x=()=>h.current=!1;return document.addEventListener("keydown",y,{capture:!0}),()=>{document.removeEventListener("keydown",y,{capture:!0}),document.removeEventListener("pointerdown",x,{capture:!0}),document.removeEventListener("pointermove",x,{capture:!0})}},[]),f.createElement(Od,l,f.createElement(K3,{scope:t,open:n,onOpenChange:m,content:u,onContentChange:d},f.createElement(rQ,{scope:t,onClose:f.useCallback(()=>m(!1),[m]),isUsingKeyboardRef:h,dir:g,modal:s},r)))},Y3=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,o=pg(n);return f.createElement(zm,Y({},o,r,{ref:t}))}),G3="MenuPortal",[iQ,X3]=Na(G3,{forceMount:void 0}),sQ=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:o}=e,i=Fs(G3,t);return f.createElement(iQ,{scope:t,forceMount:n},f.createElement(bn,{present:n||i.open},f.createElement(Md,{asChild:!0,container:o},r)))},yo="MenuContent",[aQ,Jx]=Na(yo),lQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},s.modal?f.createElement(cQ,Y({},o,{ref:t})):f.createElement(uQ,Y({},o,{ref:t})))))}),cQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu),r=f.useRef(null),o=Be(t,r);return f.useEffect(()=>{const i=r.current;if(i)return Xm(i)},[]),f.createElement(eb,Y({},e,{ref:o,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:ue(e.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)}))}),uQ=f.forwardRef((e,t)=>{const n=Fs(yo,e.__scopeMenu);return f.createElement(eb,Y({},e,{ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)}))}),eb=f.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:o,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y,disableOutsideScroll:x,..._}=e,C=Fs(yo,n),S=Hd(yo,n),b=pg(n),E=H3(n),k=tQ(n),[P,M]=f.useState(null),A=f.useRef(null),O=Be(t,A,C.onContentChange),F=f.useRef(0),V=f.useRef(""),J=f.useRef(0),G=f.useRef(null),ae=f.useRef("right"),U=f.useRef(0),te=x?Gm:f.Fragment,L=x?{as:Wo,allowPinchZoom:!0}:void 0,ie=Q=>{var W,le;const ge=V.current+Q,Ve=k().filter($e=>!$e.disabled),Ue=document.activeElement,We=(W=Ve.find($e=>$e.ref.current===Ue))===null||W===void 0?void 0:W.textValue,Me=Ve.map($e=>$e.textValue),fe=kQ(Me,ge,We),xe=(le=Ve.find($e=>$e.textValue===fe))===null||le===void 0?void 0:le.ref.current;(function $e(Ae){V.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>$e(""),1e3))})(ge),xe&&setTimeout(()=>xe.focus())};f.useEffect(()=>()=>window.clearTimeout(F.current),[]),Km();const K=f.useCallback(Q=>{var W,le;return ae.current===((W=G.current)===null||W===void 0?void 0:W.side)&&TQ(Q,(le=G.current)===null||le===void 0?void 0:le.area)},[]);return f.createElement(aQ,{scope:n,searchRef:V,onItemEnter:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),onItemLeave:f.useCallback(Q=>{var W;K(Q)||((W=A.current)===null||W===void 0||W.focus(),M(null))},[K]),onTriggerLeave:f.useCallback(Q=>{K(Q)&&Q.preventDefault()},[K]),pointerGraceTimerRef:J,onPointerGraceIntentChange:f.useCallback(Q=>{G.current=Q},[])},f.createElement(te,L,f.createElement(Hm,{asChild:!0,trapped:o,onMountAutoFocus:ue(i,Q=>{var W;Q.preventDefault(),(W=A.current)===null||W===void 0||W.focus()}),onUnmountAutoFocus:s},f.createElement(yc,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:g,onDismiss:y},f.createElement(ZP,Y({asChild:!0},E,{dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:M,onEntryFocus:ue(u,Q=>{S.isUsingKeyboardRef.current||Q.preventDefault()})}),f.createElement(Bm,Y({role:"menu","aria-orientation":"vertical","data-state":tA(C.open),"data-radix-menu-content":"",dir:S.dir},b,_,{ref:O,style:{outline:"none",..._.style},onKeyDown:ue(_.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,ge=Q.ctrlKey||Q.altKey||Q.metaKey,Ve=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!ge&&Ve&&ie(Q.key));const Ue=A.current;if(Q.target!==Ue||!Qq.includes(Q.key))return;Q.preventDefault();const Me=k().filter(fe=>!fe.disabled).map(fe=>fe.ref.current);V3.includes(Q.key)&&Me.reverse(),CQ(Me)}),onBlur:ue(e.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(F.current),V.current="")}),onPointerMove:ue(e.onPointerMove,cd(Q=>{const W=Q.target,le=U.current!==Q.clientX;if(Q.currentTarget.contains(W)&&le){const ge=Q.clientX>U.current?"right":"left";ae.current=ge,U.current=Q.clientX}}))})))))))}),dQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),U1="MenuItem",H2="menu.itemSelect",tb=f.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...o}=e,i=f.useRef(null),s=Hd(U1,e.__scopeMenu),l=Jx(U1,e.__scopeMenu),u=Be(t,i),d=f.useRef(!1),h=()=>{const m=i.current;if(!n&&m){const g=new CustomEvent(H2,{bubbles:!0,cancelable:!0});m.addEventListener(H2,y=>r==null?void 0:r(y),{once:!0}),cx(m,g),g.defaultPrevented?d.current=!1:s.onClose()}};return f.createElement(Z3,Y({},o,{ref:u,disabled:n,onClick:ue(e.onClick,h),onPointerDown:m=>{var g;(g=e.onPointerDown)===null||g===void 0||g.call(e,m),d.current=!0},onPointerUp:ue(e.onPointerUp,m=>{var g;d.current||(g=m.currentTarget)===null||g===void 0||g.click()}),onKeyDown:ue(e.onKeyDown,m=>{const g=l.searchRef.current!=="";n||g&&m.key===" "||B1.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})}))}),Z3=f.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:o,...i}=e,s=Jx(U1,n),l=H3(n),u=f.useRef(null),d=Be(t,u),[h,m]=f.useState(!1),[g,y]=f.useState("");return f.useEffect(()=>{const x=u.current;if(x){var _;y(((_=x.textContent)!==null&&_!==void 0?_:"").trim())}},[i.children]),f.createElement(ld.ItemSlot,{scope:n,disabled:r,textValue:o??g},f.createElement(qP,Y({asChild:!0},l,{focusable:!r}),f.createElement(Pe.div,Y({role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0},i,{ref:d,onPointerMove:ue(e.onPointerMove,cd(x=>{r?s.onItemLeave(x):(s.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus())})),onPointerLeave:ue(e.onPointerLeave,cd(x=>s.onItemLeave(x))),onFocus:ue(e.onFocus,()=>m(!0)),onBlur:ue(e.onBlur,()=>m(!1))}))))}),fQ=f.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...o}=e;return f.createElement(Q3,{scope:e.__scopeMenu,checked:n},f.createElement(tb,Y({role:"menuitemcheckbox","aria-checked":om(n)?"mixed":n},o,{ref:t,"data-state":nb(n),onSelect:ue(o.onSelect,()=>r==null?void 0:r(om(n)?!0:!n),{checkForDefaultPrevented:!1})})))}),pQ="MenuRadioGroup",[Cte,hQ]=Na(pQ,{value:void 0,onValueChange:()=>{}}),mQ="MenuRadioItem",gQ=f.forwardRef((e,t)=>{const{value:n,...r}=e,o=hQ(mQ,e.__scopeMenu),i=n===o.value;return f.createElement(Q3,{scope:e.__scopeMenu,checked:i},f.createElement(tb,Y({role:"menuitemradio","aria-checked":i},r,{ref:t,"data-state":nb(i),onSelect:ue(r.onSelect,()=>{var s;return(s=o.onValueChange)===null||s===void 0?void 0:s.call(o,n)},{checkForDefaultPrevented:!1})})))}),q3="MenuItemIndicator",[Q3,vQ]=Na(q3,{checked:!1}),yQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...o}=e,i=vQ(q3,n);return f.createElement(bn,{present:r||om(i.checked)||i.checked===!0},f.createElement(Pe.span,Y({},o,{ref:t,"data-state":nb(i.checked)})))}),wQ=f.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return f.createElement(Pe.div,Y({role:"separator","aria-orientation":"horizontal"},r,{ref:t}))}),J3="MenuSub",[xQ,eA]=Na(J3),bQ=e=>{const{__scopeMenu:t,children:n,open:r=!1,onOpenChange:o}=e,i=Fs(J3,t),s=pg(t),[l,u]=f.useState(null),[d,h]=f.useState(null),m=Ft(o);return f.useEffect(()=>(i.open===!1&&m(!1),()=>m(!1)),[i.open,m]),f.createElement(Od,s,f.createElement(K3,{scope:t,open:r,onOpenChange:m,content:d,onContentChange:h},f.createElement(xQ,{scope:t,contentId:nr(),triggerId:nr(),trigger:l,onTriggerChange:u},n)))},gp="MenuSubTrigger",_Q=f.forwardRef((e,t)=>{const n=Fs(gp,e.__scopeMenu),r=Hd(gp,e.__scopeMenu),o=eA(gp,e.__scopeMenu),i=Jx(gp,e.__scopeMenu),s=f.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=i,d={__scopeMenu:e.__scopeMenu},h=f.useCallback(()=>{s.current&&window.clearTimeout(s.current),s.current=null},[]);return f.useEffect(()=>h,[h]),f.useEffect(()=>{const m=l.current;return()=>{window.clearTimeout(m),u(null)}},[l,u]),f.createElement(Y3,Y({asChild:!0},d),f.createElement(Z3,Y({id:o.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":o.contentId,"data-state":tA(n.open)},e,{ref:Am(t,o.onTriggerChange),onClick:m=>{var g;(g=e.onClick)===null||g===void 0||g.call(e,m),!(e.disabled||m.defaultPrevented)&&(m.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:ue(e.onPointerMove,cd(m=>{i.onItemEnter(m),!m.defaultPrevented&&!e.disabled&&!n.open&&!s.current&&(i.onPointerGraceIntentChange(null),s.current=window.setTimeout(()=>{n.onOpenChange(!0),h()},100))})),onPointerLeave:ue(e.onPointerLeave,cd(m=>{var g;h();const y=(g=n.content)===null||g===void 0?void 0:g.getBoundingClientRect();if(y){var x;const _=(x=n.content)===null||x===void 0?void 0:x.dataset.side,C=_==="right",S=C?-5:5,b=y[C?"left":"right"],E=y[C?"right":"left"];i.onPointerGraceIntentChange({area:[{x:m.clientX+S,y:m.clientY},{x:b,y:y.top},{x:E,y:y.top},{x:E,y:y.bottom},{x:b,y:y.bottom}],side:_}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(m),m.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:ue(e.onKeyDown,m=>{const g=i.searchRef.current!=="";if(!(e.disabled||g&&m.key===" ")&&Jq[r.dir].includes(m.key)){var y;n.onOpenChange(!0),(y=n.content)===null||y===void 0||y.focus(),m.preventDefault()}})})))}),SQ="MenuSubContent",EQ=f.forwardRef((e,t)=>{const n=X3(yo,e.__scopeMenu),{forceMount:r=n.forceMount,...o}=e,i=Fs(yo,e.__scopeMenu),s=Hd(yo,e.__scopeMenu),l=eA(SQ,e.__scopeMenu),u=f.useRef(null),d=Be(t,u);return f.createElement(ld.Provider,{scope:e.__scopeMenu},f.createElement(bn,{present:r||i.open},f.createElement(ld.Slot,{scope:e.__scopeMenu},f.createElement(eb,Y({id:l.contentId,"aria-labelledby":l.triggerId},o,{ref:d,align:"start",side:s.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:h=>{var m;s.isUsingKeyboardRef.current&&((m=u.current)===null||m===void 0||m.focus()),h.preventDefault()},onCloseAutoFocus:h=>h.preventDefault(),onFocusOutside:ue(e.onFocusOutside,h=>{h.target!==l.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:ue(e.onEscapeKeyDown,h=>{s.onClose(),h.preventDefault()}),onKeyDown:ue(e.onKeyDown,h=>{const m=h.currentTarget.contains(h.target),g=eQ[s.dir].includes(h.key);if(m&&g){var y;i.onOpenChange(!1),(y=l.trigger)===null||y===void 0||y.focus(),h.preventDefault()}})})))))});function tA(e){return e?"open":"closed"}function om(e){return e==="indeterminate"}function nb(e){return om(e)?"indeterminate":e?"checked":"unchecked"}function CQ(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function $Q(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function kQ(e,t,n){const o=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?e.indexOf(n):-1;let s=$Q(e,Math.max(i,0));o.length===1&&(s=s.filter(d=>d!==n));const u=s.find(d=>d.toLowerCase().startsWith(o.toLowerCase()));return u!==n?u:void 0}function RQ(e,t){const{x:n,y:r}=e;let o=!1;for(let i=0,s=t.length-1;ir!=h>r&&n<(d-l)*(r-u)/(h-u)+l&&(o=!o)}return o}function TQ(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return RQ(n,t)}function cd(e){return t=>t.pointerType==="mouse"?e(t):void 0}const PQ=oQ,AQ=Y3,OQ=sQ,MQ=lQ,NQ=dQ,DQ=tb,IQ=fQ,LQ=gQ,FQ=yQ,jQ=wQ,zQ=bQ,BQ=_Q,UQ=EQ,nA="DropdownMenu",[VQ,$te]=An(nA,[W3]),Sr=W3(),[WQ,rA]=VQ(nA),HQ=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:o,defaultOpen:i,onOpenChange:s,modal:l=!0}=e,u=Sr(t),d=f.useRef(null),[h=!1,m]=Zr({prop:o,defaultProp:i,onChange:s});return f.createElement(WQ,{scope:t,triggerId:nr(),triggerRef:d,contentId:nr(),open:h,onOpenChange:m,onOpenToggle:f.useCallback(()=>m(g=>!g),[m]),modal:l},f.createElement(PQ,Y({},u,{open:h,onOpenChange:m,dir:r,modal:l}),n))},KQ="DropdownMenuTrigger",YQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...o}=e,i=rA(KQ,n),s=Sr(n);return f.createElement(AQ,Y({asChild:!0},s),f.createElement(Pe.button,Y({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:Am(t,i.triggerRef),onPointerDown:ue(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(i.onOpenToggle(),i.open||l.preventDefault())}),onKeyDown:ue(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&i.onOpenToggle(),l.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})))}),GQ=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Sr(t);return f.createElement(OQ,Y({},r,n))},XQ="DropdownMenuContent",ZQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=rA(XQ,n),i=Sr(n),s=f.useRef(!1);return f.createElement(MQ,Y({id:o.contentId,"aria-labelledby":o.triggerId},i,r,{ref:t,onCloseAutoFocus:ue(e.onCloseAutoFocus,l=>{var u;s.current||(u=o.triggerRef.current)===null||u===void 0||u.focus(),s.current=!1,l.preventDefault()}),onInteractOutside:ue(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,h=u.button===2||d;(!o.modal||h)&&(s.current=!0)}),style:{...e.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)"}}))}),qQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(NQ,Y({},o,r,{ref:t}))}),QQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(DQ,Y({},o,r,{ref:t}))}),JQ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(IQ,Y({},o,r,{ref:t}))}),eJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(LQ,Y({},o,r,{ref:t}))}),tJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(FQ,Y({},o,r,{ref:t}))}),nJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(jQ,Y({},o,r,{ref:t}))}),rJ=e=>{const{__scopeDropdownMenu:t,children:n,open:r,onOpenChange:o,defaultOpen:i}=e,s=Sr(t),[l=!1,u]=Zr({prop:r,defaultProp:i,onChange:o});return f.createElement(zQ,Y({},s,{open:l,onOpenChange:u}),n)},oJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(BQ,Y({},o,r,{ref:t}))}),iJ=f.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,o=Sr(n);return f.createElement(UQ,Y({},o,r,{ref:t,style:{...e.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)"}}))}),sJ=HQ,aJ=YQ,lJ=GQ,oA=ZQ,iA=qQ,sA=QQ,aA=JQ,lA=eJ,cA=tJ,uA=nJ,cJ=rJ,dA=oJ,fA=iJ,uJ=sJ,dJ=aJ,K2=cJ,V1=f.forwardRef(({className:e,inset:t,children:n,...r},o)=>v.jsxs(dA,{ref:o,className:Ce("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...r,children:[n,v.jsx(ez,{className:"ml-auto h-4 w-4"})]}));V1.displayName=dA.displayName;const W1=f.forwardRef(({className:e,...t},n)=>v.jsx(fA,{ref:n,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...t}));W1.displayName=fA.displayName;const pA=f.forwardRef(({className:e,sideOffset:t=4,...n},r)=>v.jsx(lJ,{children:v.jsx(oA,{ref:r,sideOffset:t,className:Ce("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md","data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),onCloseAutoFocus:o=>o.preventDefault(),...n})}));pA.displayName=oA.displayName;const il=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(sA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",t&&"pl-8",e),...n}));il.displayName=sA.displayName;const fJ=f.forwardRef(({className:e,children:t,checked:n,...r},o)=>v.jsxs(aA,{ref:o,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),checked:n,...r,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(vT,{className:"h-4 w-4"})})}),t]}));fJ.displayName=aA.displayName;const pJ=f.forwardRef(({className:e,children:t,...n},r)=>v.jsxs(lA,{ref:r,className:Ce("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[v.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:v.jsx(cA,{children:v.jsx(iz,{className:"h-4 w-4 fill-current"})})}),t]}));pJ.displayName=lA.displayName;const hJ=f.forwardRef(({className:e,inset:t,...n},r)=>v.jsx(iA,{ref:r,className:Ce("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",e),...n}));hJ.displayName=iA.displayName;const mJ=f.forwardRef(({className:e,...t},n)=>v.jsx(uA,{ref:n,className:Ce("-mx-1 my-1 h-px bg-muted",e),...t}));mJ.displayName=uA.displayName;const Y2={RemoveBG:{IconClass:VC,showName:"RemoveBG"},AnimeSeg:{IconClass:VC,showName:"Anime Segmentation"},RealESRGAN:{IconClass:XT,showName:"RealESRGAN"},GFPGAN:{IconClass:WC,showName:"GFPGAN"},RestoreFormer:{IconClass:WC,showName:"RestoreFormer"},InteractiveSeg:{IconClass:nV,showName:"Interactive Segmentation"}},gJ=()=>{const[e,t,n,r]=bt(d=>[d.file,d.serverConfig.plugins,d.updateInteractiveSegState,d.runRenderablePlugin]),o=!e;if(t.length===0)return null;const i=(d,h)=>{h==="InteractiveSeg"?n({isInteractiveSeg:!0}):r(d,h)},s=()=>v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(XT,{}),"RealESRGAN"]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:2}),children:"upscale 2x"}),v.jsx(il,{onClick:()=>r(!1,"RealESRGAN",{upscale:4}),children:"upscale 4x"})]})]},"RealESRGAN"),l=d=>{const{IconClass:h,showName:m}=Y2[d.name];return v.jsxs(K2,{children:[v.jsx(V1,{disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})}),v.jsxs(W1,{children:[v.jsx(il,{onClick:()=>i(!1,d.name),children:"Remove Background"}),v.jsx(il,{onClick:()=>i(!0,d.name),children:"Generate Mask"})]})]},d.name)},u=()=>t.map(d=>{const{IconClass:h,showName:m}=Y2[d.name];return d.name==="RealESRGAN"?s():d.name==="RemoveBG"||d.name==="AnimeSeg"?l(d):v.jsx(il,{onClick:()=>i(!1,d.name),disabled:o,children:v.jsxs("div",{className:"flex gap-2 items-center",children:[v.jsx(h,{className:"p-1"}),m]})},d.name)});return v.jsxs(uJ,{modal:!1,children:[v.jsx(dJ,{className:"border rounded-lg z-10 bg-background outline-none",tabIndex:-1,children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",children:v.jsx(HU,{strokeWidth:1})})}),v.jsx(pA,{side:"bottom",align:"start",children:u()})]})},vJ=Sx,yJ=gP,wJ=Ex,hA=f.forwardRef(({className:e,...t},n)=>v.jsx(Nd,{className:Ce("fixed inset-0 z-50 bg-background/80 backdrop-blur-sm data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));hA.displayName=Nd.displayName;const xJ=Om("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-200 data-[state=open]:duration-300",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),mA=f.forwardRef(({side:e="right",className:t,children:n,...r},o)=>v.jsxs(wJ,{children:[v.jsx(hA,{}),v.jsx(Dd,{ref:o,className:Ce(xJ({side:e}),t),...r,children:n})]}));mA.displayName=Dd.displayName;const gA=({className:e,...t})=>v.jsx("div",{className:Ce("flex flex-col space-y-2 text-center sm:text-left",e),...t});gA.displayName="SheetHeader";const bJ=f.forwardRef(({className:e,...t},n)=>v.jsx(Id,{ref:n,className:Ce("text-lg font-semibold text-foreground",e),...t}));bJ.displayName=Id.displayName;const _J=f.forwardRef(({className:e,...t},n)=>v.jsx(Ld,{ref:n,className:Ce("text-sm text-muted-foreground",e),...t}));_J.displayName=Ld.displayName;const Ut=({children:e})=>v.jsx("div",{className:"flex justify-between items-center pr-2",children:e}),Pt=({text:e,toolTip:t="",url:n,htmlFor:r,disabled:o=!1})=>v.jsxs(YT,{children:[v.jsx(GT,{asChild:!0,children:v.jsx(Gx,{htmlFor:r||e.toLowerCase().replace(" ","-"),className:"font-medium",disabled:o,children:e})}),t||n?v.jsxs(xx,{className:"flex flex-col max-w-xs text-sm",side:"left",children:[v.jsx("p",{children:t}),n?v.jsx(yn,{variant:"link",className:"justify-end",children:v.jsx("a",{href:n,target:"_blank",children:"More info"})}):v.jsx(v.Fragment,{})]}):v.jsx(v.Fragment,{})]}),SJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(e.ldmSteps)],onValueChange:n=>t({ldmSteps:n[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:e.ldmSteps,allowFloat:!1,onNumberValueChange:n=>{t({ldmSteps:n})}})]})]}),v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{value:e.ldmSampler,onValueChange:n=>{t({ldmSampler:n})},children:[v.jsx(ls,{className:"w-[100px]",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(Zw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]})]})},vA=f.forwardRef(({className:e,...t},n)=>v.jsx("textarea",{className:Ce("flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",e,"overflow-auto"),tabIndex:-1,ref:n,...t}));vA.displayName="Textarea";const vp=({text:e,onClick:t})=>{const[n]=bt(r=>[r.settings.showExtender]);return v.jsx(yn,{variant:"outline",className:"p-1 h-8",disabled:!n,onClick:t,children:v.jsx("div",{className:"flex items-center gap-1",children:e})})},EJ=()=>{const[e,t,n,r,o,i,s,l,u,d,h]=bt(L=>[L.serverConfig.samplers,L.settings,L.paintByExampleFile,L.getIsProcessing(),L.updateSettings,L.runInpainting,L.updateAppState,L.updateExtenderByBuiltIn,L.updateExtenderDirection,L.adjustMask,L.clearMask]),[m,g]=Rx(n),y=f.useRef(null);OP(y,()=>{y!=null&&y.current&&y.current.blur()});const x=L=>{L.key==="Enter"&&L.ctrlKey&&t.prompt.length!==0&&i()},_=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Cropper",toolTip:"Inpainting on part of image, improve inference speed and reduce memory usage."}),v.jsx(co,{id:"cropper",checked:t.showCropper,onCheckedChange:L=>{o({showCropper:L}),L&&o({showExtender:!1})}})]}),C=()=>t.model.support_controlnet?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"ControlNet",toolTip:"Using an additional conditioning image to control how an image is generated",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#controlnet"}),v.jsx(co,{id:"controlnet",checked:t.enableControlnet,onCheckedChange:L=>{o({enableControlnet:L})}})]}),v.jsx("div",{className:"flex flex-col gap-1",children:v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:1,max:100,step:1,disabled:!t.enableControlnet,value:[Math.floor(t.controlnetConditioningScale*100)],onValueChange:L=>o({controlnetConditioningScale:L[0]/100})}),v.jsx(Gn,{id:"controlnet-weight",className:"w-[60px] rounded-full",disabled:!t.enableControlnet,numberValue:t.controlnetConditioningScale,allowFloat:!1,onNumberValueChange:L=>{o({controlnetConditioningScale:L})}})]})}),v.jsx("div",{className:"pr-2",children:v.jsxs(aa,{defaultValue:t.controlnetMethod,value:t.controlnetMethod,onValueChange:L=>{o({controlnetMethod:L})},disabled:!t.enableControlnet,children:[v.jsx(ls,{children:v.jsx(la,{placeholder:"Select control method"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(t.model.controlnets).map(L=>v.jsx(us,{value:L,children:L.split("/")[1]},L))})})]})})]}),v.jsx(Fn,{})]}):null,S=()=>t.model.support_lcm_lora?v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"LCM LoRA",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inference_with_lcm_lora",toolTip:"Enable quality image generation in typically 2-4 steps. Suggest disabling guidance_scale by setting it to 0. You can also try values between 1.0 and 2.0. When LCM Lora is enabled, LCMSampler will be used automatically."}),v.jsx(co,{id:"lcm-lora",checked:t.enableLCMLora,onCheckedChange:L=>{o({enableLCMLora:L})}})]}),v.jsx(Fn,{})]}):null,b=()=>t.model.support_freeu?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-between items-center pr-2",children:[v.jsx(Pt,{text:"FreeU",toolTip:"FreeU is a technique for improving image quality. Different models may require different FreeU-specific hyperparameters, which can be viewed in the more info section.",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/freeu"}),v.jsx(co,{id:"freeu",checked:t.enableFreeu,onCheckedChange:L=>{o({enableFreeu:L})}})]}),v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s1",text:"s1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-s2",text:"s2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-s2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.s2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,s2:L}})}})]})]}),v.jsxs("div",{className:"flex justify-center gap-6",children:[v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b1",text:"b1",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b1",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b1,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b1:L}})}})]}),v.jsxs("div",{className:"flex gap-2 items-center justify-center",children:[v.jsx(Pt,{htmlFor:"freeu-b2",text:"b2",disabled:!t.enableFreeu}),v.jsx(Gn,{id:"freeu-b2",className:"w-14",disabled:!t.enableFreeu,numberValue:t.freeuConfig.b2,allowFloat:!0,onNumberValueChange:L=>{o({freeuConfig:{...t.freeuConfig,b2:L}})}})]})]})]}),v.jsx(Fn,{})]}):null,E=()=>t.model.need_prompt?v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsx(Pt,{text:"Negative prompt",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#negative-prompt",toolTip:"Negative prompt guides the model away from generating certain things in an image"}),v.jsx("div",{className:"pl-2 pr-4",children:v.jsx(vA,{ref:y,rows:4,onKeyUp:x,className:"max-h-[8rem] overflow-y-auto mb-2",placeholder:"",id:"negative-prompt",value:t.negativePrompt,onInput:L=>{L.preventDefault(),L.stopPropagation();const ie=L.target;o({negativePrompt:ie.value})}})})]}):null,k=()=>t.model.name!==YR?null:v.jsxs("div",{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Example Image",toolTip:"An example image to guide image generation."}),v.jsx(c1,{tooltip:"Upload example image",onFileUpload:L=>{s({paintByExampleFile:L})},children:v.jsx(ZT,{})})]}),g?v.jsx("div",{className:"flex justify-center items-center",children:v.jsx("img",{src:m.src,alt:"example",className:"max-w-[200px] max-h-[200px] m-3"})}):v.jsx(v.Fragment,{}),v.jsx(yn,{variant:"default",className:"w-full",disabled:r||!g,onClick:()=>{i()},children:"Paint"})]}),P=()=>t.model.name!==aF?null:v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Image guidance scale",toolTip:"Push the generated image towards the inital image. Higher image guidance scale encourages generated images that are closely linked to the source image, usually at the expense of lower image quality.",url:"https://huggingface.co/docs/diffusers/main/en/api/pipelines/pix2pix"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[150],min:100,max:1e3,step:1,value:[Math.floor(t.p2pImageGuidanceScale*100)],onValueChange:L=>o({p2pImageGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"image-guidance-scale",className:"w-[60px] rounded-full",numberValue:t.p2pImageGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({p2pImageGuidanceScale:L})}})]})]}),M=()=>t.model.support_strength?v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Strength",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#strength",toolTip:"Strength is a measure of how much noise is added to the base image, which influences how similar the output is to the base image. Higher value means more noise and more different from the base image"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[100],min:10,max:100,step:1,value:[Math.floor(t.sdStrength*100)],onValueChange:L=>o({sdStrength:L[0]/100})}),v.jsx(Gn,{id:"strength",className:"w-[60px] rounded-full",numberValue:t.sdStrength,allowFloat:!0,onNumberValueChange:L=>{o({sdStrength:L})}})]})]}):null,A=()=>t.model.support_outpainting?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Extender",toolTip:"Perform outpainting on images to expand it's content."}),v.jsx(co,{id:"extender",checked:t.showExtender,onCheckedChange:L=>{o({showExtender:L}),L&&o({showCropper:!1})}})]}),v.jsxs(Ut,{children:[v.jsxs(aa,{defaultValue:t.extenderDirection,value:t.extenderDirection,onValueChange:L=>{u(L)},children:[v.jsx(ls,{className:"w-[65px] h-7",disabled:!t.showExtender,children:v.jsx(la,{placeholder:"Select axis"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(In).map(L=>v.jsx(us,{value:L,children:L},L))})})]}),v.jsxs("div",{className:"flex gap-1 justify-center mt-0",children:[v.jsx(vp,{text:"1.25x",onClick:()=>l(t.extenderDirection,1.25)}),v.jsx(vp,{text:"1.5x",onClick:()=>l(t.extenderDirection,1.5)}),v.jsx(vp,{text:"1.75x",onClick:()=>l(t.extenderDirection,1.75)}),v.jsx(vp,{text:"2.0x",onClick:()=>l(t.extenderDirection,2)})]})]})]}),v.jsx(Fn,{})]}):null,O=()=>t.model.name!==lF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Task",toolTip:"PowerPaint task. When using extender, image-outpainting task will be auto used. For object-removal and image-outpainting, it is recommended to set the guidance_scale at 10 or above."}),v.jsxs(aa,{defaultValue:t.powerpaintTask,value:t.powerpaintTask,onValueChange:L=>{o({powerpaintTask:L})},disabled:t.showExtender,children:[v.jsx(ls,{className:"w-[140px]",children:v.jsx(la,{placeholder:"Select task"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:[kl.text_guided,kl.object_remove,kl.shape_guided].map(L=>v.jsx(us,{value:L,children:L},L))})})]})]}),F=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"steps",text:"Steps",toolTip:"The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[30],min:1,max:100,step:1,value:[Math.floor(t.sdSteps)],onValueChange:L=>o({sdSteps:L[0]})}),v.jsx(Gn,{id:"steps",className:"w-[60px] rounded-full",numberValue:t.sdSteps,allowFloat:!1,onNumberValueChange:L=>{o({sdSteps:L})}})]})]}),V=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Guidance scale",url:"https://huggingface.co/docs/diffusers/main/en/using-diffusers/inpaint#guidance-scale",toolTip:"Guidance scale affects how aligned the text prompt and generated image are. Higher value means the prompt and generated image are closely aligned, so the output is a stricter interpretation of the prompt"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[750],min:0,max:1500,step:1,value:[Math.floor(t.sdGuidanceScale*100)],onValueChange:L=>o({sdGuidanceScale:L[0]/100})}),v.jsx(Gn,{id:"guidance-scale",className:"w-[60px] rounded-full",numberValue:t.sdGuidanceScale,allowFloat:!0,onNumberValueChange:L=>{o({sdGuidanceScale:L})}})]})]}),J=()=>t.model.name===cF?null:v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Sampler"}),v.jsxs(aa,{defaultValue:t.sdSampler,value:t.sdSampler,onValueChange:L=>{o({sdSampler:L})},children:[v.jsx(ls,{className:"w-[175px] text-xs",children:v.jsx(la,{placeholder:"Select sampler"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:e.map(L=>v.jsx(us,{value:L,className:"text-xs",children:L},L))})})]})]}),G=()=>v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Seed",toolTip:"Using same parameters and a fixed seed can generate same result image."}),v.jsxs("div",{className:"flex gap-2 justify-center items-center",children:[v.jsx(co,{id:"seed",checked:t.seedFixed,onCheckedChange:L=>{o({seedFixed:L})}}),v.jsx(Gn,{id:"seed",className:"w-[100px]",disabled:!t.seedFixed,numberValue:t.seed,allowFloat:!1,onNumberValueChange:L=>{o({seed:L})}})]})]}),ae=()=>v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{text:"Mask blur",toolTip:"How much to blur the mask before processing, in pixels. Make the generated inpainting boundaries appear more natural."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[t.sdMaskBlur],min:0,max:96,step:1,value:[Math.floor(t.sdMaskBlur)],onValueChange:L=>o({sdMaskBlur:L[0]})}),v.jsx(Gn,{id:"mask-blur",className:"w-[60px] rounded-full",numberValue:t.sdMaskBlur,allowFloat:!1,onNumberValueChange:L=>{o({sdMaskBlur:L})}})]})]}),U=()=>v.jsxs(v.Fragment,{children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"Match histograms",toolTip:"Match the inpainting result histogram to the source image histogram",url:"https://github.com/Sanster/lama-cleaner/pull/143#issuecomment-1325859307"}),v.jsx(co,{id:"match-histograms",checked:t.sdMatchHistograms,onCheckedChange:L=>{o({sdMatchHistograms:L})}})]}),v.jsx(Fn,{})]}),te=()=>v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex flex-col gap-1",children:[v.jsx(Pt,{htmlFor:"adjustMaskKernelSize",text:"Adjust Mask",toolTip:"Expand or shrink mask. Using the slider to adjust the kernel size for dilation or erosion."}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[12],min:1,max:100,step:1,value:[Math.floor(t.adjustMaskKernelSize)],onValueChange:L=>o({adjustMaskKernelSize:L[0]})}),v.jsx(Gn,{id:"adjustMaskKernelSize",className:"w-[60px] rounded-full",numberValue:t.adjustMaskKernelSize,allowFloat:!1,onNumberValueChange:L=>{o({adjustMaskKernelSize:L})}})]}),v.jsxs(Ut,{children:[v.jsxs("div",{className:"flex gap-1 justify-start",children:[v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("expand"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"expand"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("shrink"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Shrink"})}),v.jsx(yn,{variant:"outline",className:"p-1 h-8",onClick:()=>d("reverse"),disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Reverse"})})]}),v.jsx(yn,{variant:"outline",className:"p-1 h-8 justify-self-end",onClick:h,disabled:r,children:v.jsx("div",{className:"flex items-center gap-1 select-none",children:"Clear"})})]})]}),v.jsx(Fn,{})]});return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[_(),A(),te(),O(),F(),V(),P(),M(),J(),G(),E(),v.jsx(Fn,{}),C(),S(),ae(),U(),b(),k()]})},CJ=()=>{const[e,t]=bt(n=>[n.settings,n.updateSettings]);return v.jsxs("div",{className:"flex flex-col gap-4 mt-4",children:[v.jsxs(Ut,{children:[v.jsx(Pt,{text:"CV2 Flag",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(aa,{value:e.cv2Flag,onValueChange:n=>{t({cv2Flag:n})},children:[v.jsx(ls,{className:"w-[160px]",children:v.jsx(la,{placeholder:"Select flag"})}),v.jsx(cs,{align:"end",children:v.jsx(wl,{children:Object.values(qw).map(n=>v.jsx(us,{value:n,children:n},n))})})]})]}),v.jsx(Pt,{text:"CV2 Radius",url:"https://docs.opencv.org/4.8.0/d7/d8b/group__photo__inpaint.html#gga8002a65f5a3328fbf15df81b842d3c3ca892824c38e258feb5e72f308a358d52e"}),v.jsxs(Ut,{children:[v.jsx(uo,{className:"w-[180px]",defaultValue:[5],min:1,max:100,step:1,value:[Math.floor(e.cv2Radius)],onValueChange:n=>t({cv2Radius:n[0]})}),v.jsx(Gn,{id:"cv2-radius",className:"w-[60px] rounded-full",numberValue:e.cv2Radius,allowFloat:!1,onNumberValueChange:n=>{t({cv2Radius:n})}})]})]})},$J=()=>{const[e,t]=bt(i=>[i.settings,i.windowSize]),[n,r]=AP(!0);if(Zn("c",()=>{r()}),e.model.name!==oC&&e.model.name!==iC&&e.model.model_type===is)return null;const o=()=>e.model.name===oC?v.jsx(SJ,{}):e.model.name===iC?v.jsx(CJ,{}):v.jsx(EJ,{});return v.jsxs(vJ,{open:n,modal:!1,children:[v.jsx(yJ,{tabIndex:-1,className:"z-10 outline-none absolute top-[68px] right-6 rounded-lg border bg-background",children:v.jsx(yn,{variant:"ghost",size:"icon",asChild:!0,className:"p-1.5",onClick:r,children:v.jsx(KU,{strokeWidth:1})})}),v.jsxs(mA,{side:"right",className:"w-[300px] mt-[60px] outline-none pl-4 pr-1",onOpenAutoFocus:i=>i.preventDefault(),onPointerDownOutside:i=>i.preventDefault(),children:[v.jsxs(gA,{children:[v.jsxs(Ut,{children:[v.jsx("div",{className:"overflow-hidden mr-8",children:e.model.name.split("/")[e.model.name.split("/").length-1]}),v.jsx(yn,{variant:"ghost",size:"icon",className:"border h-6 w-6",onClick:r,children:v.jsx(YU,{strokeWidth:1})})]}),v.jsx(Fn,{})]}),v.jsx(og,{style:{height:t.height-160},className:"pr-3",children:o()})]})]})},Yo=Object.create(null);Yo.open="0";Yo.close="1";Yo.ping="2";Yo.pong="3";Yo.message="4";Yo.upgrade="5";Yo.noop="6";const th=Object.create(null);Object.keys(Yo).forEach(e=>{th[Yo[e]]=e});const H1={type:"error",data:"parser error"},yA=typeof Blob=="function"||typeof Blob<"u"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]",wA=typeof ArrayBuffer=="function",xA=e=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,rb=({type:e,data:t},n,r)=>yA&&t instanceof Blob?n?r(t):G2(t,r):wA&&(t instanceof ArrayBuffer||xA(t))?n?r(t):G2(new Blob([t]),r):r(Yo[e]+(t||"")),G2=(e,t)=>{const n=new FileReader;return n.onload=function(){const r=n.result.split(",")[1];t("b"+(r||""))},n.readAsDataURL(e)};function X2(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let L0;function kJ(e,t){if(yA&&e.data instanceof Blob)return e.data.arrayBuffer().then(X2).then(t);if(wA&&(e.data instanceof ArrayBuffer||xA(e.data)))return t(X2(e.data));rb(e,!1,n=>{L0||(L0=new TextEncoder),t(L0.encode(n))})}const Z2="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",gu=typeof Uint8Array>"u"?[]:new Uint8Array(256);for(let e=0;e{let t=e.length*.75,n=e.length,r,o=0,i,s,l,u;e[e.length-1]==="="&&(t--,e[e.length-2]==="="&&t--);const d=new ArrayBuffer(t),h=new Uint8Array(d);for(r=0;r>4,h[o++]=(s&15)<<4|l>>2,h[o++]=(l&3)<<6|u&63;return d},TJ=typeof ArrayBuffer=="function",ob=(e,t)=>{if(typeof e!="string")return{type:"message",data:bA(e,t)};const n=e.charAt(0);return n==="b"?{type:"message",data:PJ(e.substring(1),t)}:th[n]?e.length>1?{type:th[n],data:e.substring(1)}:{type:th[n]}:H1},PJ=(e,t)=>{if(TJ){const n=RJ(e);return bA(n,t)}else return{base64:!0,data:e}},bA=(e,t)=>{switch(t){case"blob":return e instanceof Blob?e:new Blob([e]);case"arraybuffer":default:return e instanceof ArrayBuffer?e:e.buffer}},_A="",AJ=(e,t)=>{const n=e.length,r=new Array(n);let o=0;e.forEach((i,s)=>{rb(i,!1,l=>{r[s]=l,++o===n&&t(r.join(_A))})})},OJ=(e,t)=>{const n=e.split(_A),r=[];for(let o=0;o{const r=n.length;let o;if(r<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,r);else if(r<65536){o=new Uint8Array(3);const i=new DataView(o.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{o=new Uint8Array(9);const i=new DataView(o.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}e.data&&typeof e.data!="string"&&(o[0]|=128),t.enqueue(o),t.enqueue(n)})}})}let F0;function yp(e){return e.reduce((t,n)=>t+n.length,0)}function wp(e,t){if(e[0].length===t)return e.shift();const n=new Uint8Array(t);let r=0;for(let o=0;oMath.pow(2,21)-1){l.enqueue(H1);break}o=h*Math.pow(2,32)+d.getUint32(4),r=3}else{if(yp(n)e){l.enqueue(H1);break}}}})}const SA=4;function qt(e){if(e)return DJ(e)}function DJ(e){for(var t in qt.prototype)e[t]=qt.prototype[t];return e}qt.prototype.on=qt.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this};qt.prototype.once=function(e,t){function n(){this.off(e,n),t.apply(this,arguments)}return n.fn=t,this.on(e,n),this};qt.prototype.off=qt.prototype.removeListener=qt.prototype.removeAllListeners=qt.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var n=this._callbacks["$"+e];if(!n)return this;if(arguments.length==1)return delete this._callbacks["$"+e],this;for(var r,o=0;o(e.hasOwnProperty(r)&&(n[r]=e[r]),n),{})}const IJ=Br.setTimeout,LJ=Br.clearTimeout;function hg(e,t){t.useNativeTimers?(e.setTimeoutFn=IJ.bind(Br),e.clearTimeoutFn=LJ.bind(Br)):(e.setTimeoutFn=Br.setTimeout.bind(Br),e.clearTimeoutFn=Br.clearTimeout.bind(Br))}const FJ=1.33;function jJ(e){return typeof e=="string"?zJ(e):Math.ceil((e.byteLength||e.size)*FJ)}function zJ(e){let t=0,n=0;for(let r=0,o=e.length;r=57344?n+=3:(r++,n+=4);return n}function BJ(e){let t="";for(let n in e)e.hasOwnProperty(n)&&(t.length&&(t+="&"),t+=encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t}function UJ(e){let t={},n=e.split("&");for(let r=0,o=n.length;r0);return t}function $A(){const e=J2(+new Date);return e!==Q2?(q2=0,Q2=e):e+"."+J2(q2++)}for(;xp{this.readyState="paused",t()};if(this.polling||!this.writable){let r=0;this.polling&&(r++,this.once("pollComplete",function(){--r||n()})),this.writable||(r++,this.once("drain",function(){--r||n()}))}else n()}poll(){this.polling=!0,this.doPoll(),this.emitReserved("poll")}onData(t){const n=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};OJ(t,this.socket.binaryType).forEach(n),this.readyState!=="closed"&&(this.polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"&&this.poll())}doClose(){const t=()=>{this.write([{type:"close"}])};this.readyState==="open"?t():this.once("open",t)}write(t){this.writable=!1,AJ(t,n=>{this.doWrite(n,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const t=this.opts.secure?"https":"http",n=this.query||{};return this.opts.timestampRequests!==!1&&(n[this.opts.timestampParam]=$A()),!this.supportsBinary&&!n.sid&&(n.b64=1),this.createUri(t,n)}request(t={}){return Object.assign(t,{xd:this.xd,cookieJar:this.cookieJar},this.opts),new Vo(this.uri(),t)}doWrite(t,n){const r=this.request({method:"POST",data:t});r.on("success",n),r.on("error",(o,i)=>{this.onError("xhr post error",o,i)})}doPoll(){const t=this.request();t.on("data",this.onData.bind(this)),t.on("error",(n,r)=>{this.onError("xhr poll error",n,r)}),this.pollXhr=t}}class Vo extends qt{constructor(t,n){super(),hg(this,n),this.opts=n,this.method=n.method||"GET",this.uri=t,this.data=n.data!==void 0?n.data:null,this.create()}create(){var t;const n=EA(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");n.xdomain=!!this.opts.xd;const r=this.xhr=new RA(n);try{r.open(this.method,this.uri,!0);try{if(this.opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let o in this.opts.extraHeaders)this.opts.extraHeaders.hasOwnProperty(o)&&r.setRequestHeader(o,this.opts.extraHeaders[o])}}catch{}if(this.method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(t=this.opts.cookieJar)===null||t===void 0||t.addCookies(r),"withCredentials"in r&&(r.withCredentials=this.opts.withCredentials),this.opts.requestTimeout&&(r.timeout=this.opts.requestTimeout),r.onreadystatechange=()=>{var o;r.readyState===3&&((o=this.opts.cookieJar)===null||o===void 0||o.parseCookies(r)),r.readyState===4&&(r.status===200||r.status===1223?this.onLoad():this.setTimeoutFn(()=>{this.onError(typeof r.status=="number"?r.status:0)},0))},r.send(this.data)}catch(o){this.setTimeoutFn(()=>{this.onError(o)},0);return}typeof document<"u"&&(this.index=Vo.requestsCount++,Vo.requests[this.index]=this)}onError(t){this.emitReserved("error",t,this.xhr),this.cleanup(!0)}cleanup(t){if(!(typeof this.xhr>"u"||this.xhr===null)){if(this.xhr.onreadystatechange=KJ,t)try{this.xhr.abort()}catch{}typeof document<"u"&&delete Vo.requests[this.index],this.xhr=null}}onLoad(){const t=this.xhr.responseText;t!==null&&(this.emitReserved("data",t),this.emitReserved("success"),this.cleanup())}abort(){this.cleanup()}}Vo.requestsCount=0;Vo.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",e$);else if(typeof addEventListener=="function"){const e="onpagehide"in Br?"pagehide":"unload";addEventListener(e,e$,!1)}}function e$(){for(let e in Vo.requests)Vo.requests.hasOwnProperty(e)&&Vo.requests[e].abort()}const sb=typeof Promise=="function"&&typeof Promise.resolve=="function"?t=>Promise.resolve().then(t):(t,n)=>n(t,0),bp=Br.WebSocket||Br.MozWebSocket,t$=!0,XJ="arraybuffer",n$=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative";class ZJ extends ib{constructor(t){super(t),this.supportsBinary=!t.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check())return;const t=this.uri(),n=this.opts.protocols,r=n$?{}:EA(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=t$&&!n$?n?new bp(t,n):new bp(t):new bp(t,n,r)}catch(o){return this.emitReserved("error",o)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=t=>this.onClose({description:"websocket connection closed",context:t}),this.ws.onmessage=t=>this.onData(t.data),this.ws.onerror=t=>this.onError("websocket error",t)}write(t){this.writable=!1;for(let n=0;n{const s={};try{t$&&this.ws.send(i)}catch{}o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.close(),this.ws=null)}uri(){const t=this.opts.secure?"wss":"ws",n=this.query||{};return this.opts.timestampRequests&&(n[this.opts.timestampParam]=$A()),this.supportsBinary||(n.b64=1),this.createUri(t,n)}check(){return!!bp}}class qJ extends ib{get name(){return"webtransport"}doOpen(){typeof WebTransport=="function"&&(this.transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name]),this.transport.closed.then(()=>{this.onClose()}).catch(t=>{this.onError("webtransport error",t)}),this.transport.ready.then(()=>{this.transport.createBidirectionalStream().then(t=>{const n=NJ(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=t.readable.pipeThrough(n).getReader(),o=MJ();o.readable.pipeTo(t.writable),this.writer=o.writable.getWriter();const i=()=>{r.read().then(({done:l,value:u})=>{l||(this.onPacket(u),i())}).catch(l=>{})};i();const s={type:"open"};this.query.sid&&(s.data=`{"sid":"${this.query.sid}"}`),this.writer.write(s).then(()=>this.onOpen())})}))}write(t){this.writable=!1;for(let n=0;n{o&&sb(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var t;(t=this.transport)===null||t===void 0||t.close()}}const QJ={websocket:ZJ,webtransport:qJ,polling:GJ},JJ=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,eee=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function Y1(e){if(e.length>2e3)throw"URI too long";const t=e,n=e.indexOf("["),r=e.indexOf("]");n!=-1&&r!=-1&&(e=e.substring(0,n)+e.substring(n,r).replace(/:/g,";")+e.substring(r,e.length));let o=JJ.exec(e||""),i={},s=14;for(;s--;)i[eee[s]]=o[s]||"";return n!=-1&&r!=-1&&(i.source=t,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=tee(i,i.path),i.queryKey=nee(i,i.query),i}function tee(e,t){const n=/\/{2,9}/g,r=t.replace(n,"/").split("/");return(t.slice(0,1)=="/"||t.length===0)&&r.splice(0,1),t.slice(-1)=="/"&&r.splice(r.length-1,1),r}function nee(e,t){const n={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,o,i){o&&(n[o]=i)}),n}let TA=class sl extends qt{constructor(t,n={}){super(),this.binaryType=XJ,this.writeBuffer=[],t&&typeof t=="object"&&(n=t,t=null),t?(t=Y1(t),n.hostname=t.host,n.secure=t.protocol==="https"||t.protocol==="wss",n.port=t.port,t.query&&(n.query=t.query)):n.host&&(n.hostname=Y1(n.host).host),hg(this,n),this.secure=n.secure!=null?n.secure:typeof location<"u"&&location.protocol==="https:",n.hostname&&!n.port&&(n.port=this.secure?"443":"80"),this.hostname=n.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=n.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=n.transports||["polling","websocket","webtransport"],this.writeBuffer=[],this.prevBufferLen=0,this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},n),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=UJ(this.opts.query)),this.id=null,this.upgrades=null,this.pingInterval=null,this.pingTimeout=null,this.pingTimeoutTimer=null,typeof addEventListener=="function"&&(this.opts.closeOnBeforeunload&&(this.beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this.beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(this.offlineEventListener=()=>{this.onClose("transport close",{description:"network connection lost"})},addEventListener("offline",this.offlineEventListener,!1))),this.open()}createTransport(t){const n=Object.assign({},this.opts.query);n.EIO=SA,n.transport=t,this.id&&(n.sid=this.id);const r=Object.assign({},this.opts,{query:n,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[t]);return new QJ[t](r)}open(){let t;if(this.opts.rememberUpgrade&&sl.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1)t="websocket";else if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}else t=this.transports[0];this.readyState="opening";try{t=this.createTransport(t)}catch{this.transports.shift(),this.open();return}t.open(),this.setTransport(t)}setTransport(t){this.transport&&this.transport.removeAllListeners(),this.transport=t,t.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",n=>this.onClose("transport close",n))}probe(t){let n=this.createTransport(t),r=!1;sl.priorWebsocketSuccess=!1;const o=()=>{r||(n.send([{type:"ping",data:"probe"}]),n.once("packet",m=>{if(!r)if(m.type==="pong"&&m.data==="probe"){if(this.upgrading=!0,this.emitReserved("upgrading",n),!n)return;sl.priorWebsocketSuccess=n.name==="websocket",this.transport.pause(()=>{r||this.readyState!=="closed"&&(h(),this.setTransport(n),n.send([{type:"upgrade"}]),this.emitReserved("upgrade",n),n=null,this.upgrading=!1,this.flush())})}else{const g=new Error("probe error");g.transport=n.name,this.emitReserved("upgradeError",g)}}))};function i(){r||(r=!0,h(),n.close(),n=null)}const s=m=>{const g=new Error("probe error: "+m);g.transport=n.name,i(),this.emitReserved("upgradeError",g)};function l(){s("transport closed")}function u(){s("socket closed")}function d(m){n&&m.name!==n.name&&i()}const h=()=>{n.removeListener("open",o),n.removeListener("error",s),n.removeListener("close",l),this.off("close",u),this.off("upgrading",d)};n.once("open",o),n.once("error",s),n.once("close",l),this.once("close",u),this.once("upgrading",d),this.upgrades.indexOf("webtransport")!==-1&&t!=="webtransport"?this.setTimeoutFn(()=>{r||n.open()},200):n.open()}onOpen(){if(this.readyState="open",sl.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush(),this.readyState==="open"&&this.opts.upgrade){let t=0;const n=this.upgrades.length;for(;t{this.onClose("ping timeout")},this.pingInterval+this.pingTimeout),this.opts.autoUnref&&this.pingTimeoutTimer.unref()}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen),this.prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const t=this.getWritablePackets();this.transport.send(t),this.prevBufferLen=t.length,this.emitReserved("flush")}}getWritablePackets(){if(!(this.maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let n=1;for(let r=0;r0&&n>this.maxPayload)return this.writeBuffer.slice(0,r);n+=2}return this.writeBuffer}write(t,n,r){return this.sendPacket("message",t,n,r),this}send(t,n,r){return this.sendPacket("message",t,n,r),this}sendPacket(t,n,r,o){if(typeof n=="function"&&(o=n,n=void 0),typeof r=="function"&&(o=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;const i={type:t,data:n,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),o&&this.once("flush",o),this.flush()}close(){const t=()=>{this.onClose("forced close"),this.transport.close()},n=()=>{this.off("upgrade",n),this.off("upgradeError",n),t()},r=()=>{this.once("upgrade",n),this.once("upgradeError",n)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():t()}):this.upgrading?r():t()),this}onError(t){sl.priorWebsocketSuccess=!1,this.emitReserved("error",t),this.onClose("transport error",t)}onClose(t,n){(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")&&(this.clearTimeoutFn(this.pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),typeof removeEventListener=="function"&&(removeEventListener("beforeunload",this.beforeunloadEventListener,!1),removeEventListener("offline",this.offlineEventListener,!1)),this.readyState="closed",this.id=null,this.emitReserved("close",t,n),this.writeBuffer=[],this.prevBufferLen=0)}filterUpgrades(t){const n=[];let r=0;const o=t.length;for(;rtypeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer,PA=Object.prototype.toString,see=typeof Blob=="function"||typeof Blob<"u"&&PA.call(Blob)==="[object BlobConstructor]",aee=typeof File=="function"||typeof File<"u"&&PA.call(File)==="[object FileConstructor]";function ab(e){return oee&&(e instanceof ArrayBuffer||iee(e))||see&&e instanceof Blob||aee&&e instanceof File}function nh(e,t){if(!e||typeof e!="object")return!1;if(Array.isArray(e)){for(let n=0,r=e.length;n=0&&e.num{delete this.acks[t];for(let s=0;s{this.io.clearTimeoutFn(i),n.apply(this,[null,...s])}}emitWithAck(t,...n){const r=this.flags.timeout!==void 0||this._opts.ackTimeout!==void 0;return new Promise((o,i)=>{n.push((s,l)=>r?s?i(s):o(l):o(s)),this.emit(t,...n)})}_addToQueue(t){let n;typeof t[t.length-1]=="function"&&(n=t.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:t,flags:Object.assign({fromQueue:!0},this.flags)};t.push((o,...i)=>r!==this._queue[0]?void 0:(o!==null?r.tryCount>this._opts.retries&&(this._queue.shift(),n&&n(o)):(this._queue.shift(),n&&n(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(t=!1){if(!this.connected||this._queue.length===0)return;const n=this._queue[0];n.pending&&!t||(n.pending=!0,n.tryCount++,this.flags=n.flags,this.emit.apply(this,n.args))}packet(t){t.nsp=this.nsp,this.io._packet(t)}onopen(){typeof this.auth=="function"?this.auth(t=>{this._sendConnectPacket(t)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(t){this.packet({type:lt.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},t):t})}onerror(t){this.connected||this.emitReserved("connect_error",t)}onclose(t,n){this.connected=!1,delete this.id,this.emitReserved("disconnect",t,n)}onpacket(t){if(t.nsp===this.nsp)switch(t.type){case lt.CONNECT:t.data&&t.data.sid?this.onconnect(t.data.sid,t.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case lt.EVENT:case lt.BINARY_EVENT:this.onevent(t);break;case lt.ACK:case lt.BINARY_ACK:this.onack(t);break;case lt.DISCONNECT:this.ondisconnect();break;case lt.CONNECT_ERROR:this.destroy();const r=new Error(t.data.message);r.data=t.data.data,this.emitReserved("connect_error",r);break}}onevent(t){const n=t.data||[];t.id!=null&&n.push(this.ack(t.id)),this.connected?this.emitEvent(n):this.receiveBuffer.push(Object.freeze(n))}emitEvent(t){if(this._anyListeners&&this._anyListeners.length){const n=this._anyListeners.slice();for(const r of n)r.apply(this,t)}super.emit.apply(this,t),this._pid&&t.length&&typeof t[t.length-1]=="string"&&(this._lastOffset=t[t.length-1])}ack(t){const n=this;let r=!1;return function(...o){r||(r=!0,n.packet({type:lt.ACK,id:t,data:o}))}}onack(t){const n=this.acks[t.id];typeof n=="function"&&(n.apply(this,t.data),delete this.acks[t.id])}onconnect(t,n){this.id=t,this.recovered=n&&this._pid===n,this._pid=n,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(t=>this.emitEvent(t)),this.receiveBuffer=[],this.sendBuffer.forEach(t=>{this.notifyOutgoingListeners(t),this.packet(t)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(t=>t()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:lt.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(t){return this.flags.compress=t,this}get volatile(){return this.flags.volatile=!0,this}timeout(t){return this.flags.timeout=t,this}onAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(t),this}prependAny(t){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(t),this}offAny(t){if(!this._anyListeners)return this;if(t){const n=this._anyListeners;for(let r=0;r0&&e.jitter<=1?e.jitter:0,this.attempts=0}Cc.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),n=Math.floor(t*this.jitter*e);e=Math.floor(t*10)&1?e+n:e-n}return Math.min(e,this.max)|0};Cc.prototype.reset=function(){this.attempts=0};Cc.prototype.setMin=function(e){this.ms=e};Cc.prototype.setMax=function(e){this.max=e};Cc.prototype.setJitter=function(e){this.jitter=e};class Z1 extends qt{constructor(t,n){var r;super(),this.nsps={},this.subs=[],t&&typeof t=="object"&&(n=t,t=void 0),n=n||{},n.path=n.path||"/socket.io",this.opts=n,hg(this,n),this.reconnection(n.reconnection!==!1),this.reconnectionAttempts(n.reconnectionAttempts||1/0),this.reconnectionDelay(n.reconnectionDelay||1e3),this.reconnectionDelayMax(n.reconnectionDelayMax||5e3),this.randomizationFactor((r=n.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Cc({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(n.timeout==null?2e4:n.timeout),this._readyState="closed",this.uri=t;const o=n.parser||hee;this.encoder=new o.Encoder,this.decoder=new o.Decoder,this._autoConnect=n.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(t){return arguments.length?(this._reconnection=!!t,this):this._reconnection}reconnectionAttempts(t){return t===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=t,this)}reconnectionDelay(t){var n;return t===void 0?this._reconnectionDelay:(this._reconnectionDelay=t,(n=this.backoff)===null||n===void 0||n.setMin(t),this)}randomizationFactor(t){var n;return t===void 0?this._randomizationFactor:(this._randomizationFactor=t,(n=this.backoff)===null||n===void 0||n.setJitter(t),this)}reconnectionDelayMax(t){var n;return t===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=t,(n=this.backoff)===null||n===void 0||n.setMax(t),this)}timeout(t){return arguments.length?(this._timeout=t,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(t){if(~this._readyState.indexOf("open"))return this;this.engine=new TA(this.uri,this.opts);const n=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const o=fo(n,"open",function(){r.onopen(),t&&t()}),i=l=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",l),t?t(l):this.maybeReconnectOnOpen()},s=fo(n,"error",i);if(this._timeout!==!1){const l=this._timeout,u=this.setTimeoutFn(()=>{o(),i(new Error("timeout")),n.close()},l);this.opts.autoUnref&&u.unref(),this.subs.push(()=>{this.clearTimeoutFn(u)})}return this.subs.push(o),this.subs.push(s),this}connect(t){return this.open(t)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const t=this.engine;this.subs.push(fo(t,"ping",this.onping.bind(this)),fo(t,"data",this.ondata.bind(this)),fo(t,"error",this.onerror.bind(this)),fo(t,"close",this.onclose.bind(this)),fo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(t){try{this.decoder.add(t)}catch(n){this.onclose("parse error",n)}}ondecoded(t){sb(()=>{this.emitReserved("packet",t)},this.setTimeoutFn)}onerror(t){this.emitReserved("error",t)}socket(t,n){let r=this.nsps[t];return r?this._autoConnect&&!r.active&&r.connect():(r=new AA(this,t,n),this.nsps[t]=r),r}_destroy(t){const n=Object.keys(this.nsps);for(const r of n)if(this.nsps[r].active)return;this._close()}_packet(t){const n=this.encoder.encode(t);for(let r=0;rt()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close"),this.engine&&this.engine.close()}disconnect(){return this._close()}onclose(t,n){this.cleanup(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",t,n),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const t=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const n=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{t.skipReconnect||(this.emitReserved("reconnect_attempt",t.backoff.attempts),!t.skipReconnect&&t.open(o=>{o?(t._reconnecting=!1,t.reconnect(),this.emitReserved("reconnect_error",o)):t.onreconnect()}))},n);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const t=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",t)}}const cu={};function rh(e,t){typeof e=="object"&&(t=e,e=void 0),t=t||{};const n=ree(e,t.path||"/socket.io"),r=n.source,o=n.id,i=n.path,s=cu[o]&&i in cu[o].nsps,l=t.forceNew||t["force new connection"]||t.multiplex===!1||s;let u;return l?u=new Z1(r,t):(cu[o]||(cu[o]=new Z1(r,t)),u=cu[o]),n.query&&!t.query&&(t.query=n.queryKey),u.socket(n.path,t)}Object.assign(rh,{Manager:Z1,Socket:AA,io:rh,connect:rh});const OA="Progress",mg=100,[gee,kte]=An(OA),[vee,yee]=gee(OA),MA=f.forwardRef((e,t)=>{const{__scopeProgress:n,value:r,max:o,getValueLabel:i=bee,...s}=e,l=q1(o)?o:mg,u=DA(r,l)?r:null,d=im(u)?i(u,l):void 0;return f.createElement(vee,{scope:n,value:u,max:l},f.createElement(Pe.div,Y({"aria-valuemax":l,"aria-valuemin":0,"aria-valuenow":im(u)?u:void 0,"aria-valuetext":d,role:"progressbar","data-state":NA(u,l),"data-value":u??void 0,"data-max":l},s,{ref:t})))});MA.propTypes={max(e,t,n){const r=e[t],o=String(r);return r&&!q1(r)?new Error(_ee(o,n)):null},value(e,t,n){const r=e[t],o=String(r),i=q1(e.max)?e.max:mg;return r!=null&&!DA(r,i)?new Error(See(o,n)):null}};const wee="ProgressIndicator",xee=f.forwardRef((e,t)=>{var n;const{__scopeProgress:r,...o}=e,i=yee(wee,r);return f.createElement(Pe.div,Y({"data-state":NA(i.value,i.max),"data-value":(n=i.value)!==null&&n!==void 0?n:void 0,"data-max":i.max},o,{ref:t}))});function bee(e,t){return`${Math.round(e/t*100)}%`}function NA(e,t){return e==null?"indeterminate":e===t?"complete":"loading"}function im(e){return typeof e=="number"}function q1(e){return im(e)&&!isNaN(e)&&e>0}function DA(e,t){return im(e)&&!isNaN(e)&&e<=t&&e>=0}function _ee(e,t){return`Invalid prop \`max\` of value \`${e}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${mg}\`.`}function See(e,t){return`Invalid prop \`value\` of value \`${e}\` supplied to \`${t}\`. The \`value\` prop must be: + - a positive number + - less than the value passed to \`max\` (or ${mg} if no \`max\` prop is set) + - \`null\` if the progress is indeterminate. + +Defaulting to \`null\`.`}const IA=MA,Eee=xee,LA=f.forwardRef(({className:e,value:t,...n},r)=>v.jsx(IA,{ref:r,className:Ce("relative h-2 w-full overflow-hidden rounded-full bg-primary/20",e),...n,children:v.jsx(Eee,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));LA.displayName=IA.displayName;const Cee="",Vi=rh(Cee),$ee=()=>{const[e,t,n]=bt(u=>[u.settings,u.isInpainting,u.isSD()]),[r,o]=f.useState(!1),[i,s]=f.useState(0),l=Math.min(Math.round(i/e.sdSteps*100),100);return f.useEffect(()=>(Vi.on("connect",()=>{o(!0)}),Vi.on("disconnect",()=>{o(!1)}),Vi.on("diffusion_progress",u=>{u&&s(u.step+1)}),Vi.on("diffusion_finish",()=>{s(0)}),()=>{Vi.off("connect"),Vi.off("disconnect"),Vi.off("diffusion_progress"),Vi.off("diffusion_finish")}),[]),v.jsxs("div",{className:"z-10 fixed bg-background w-[220px] left-1/2 -translate-x-1/2 top-[68px] h-[32px] flex justify-center items-center gap-[18px] border-[1px] border-[solid] rounded-[14px] pl-[8px] pr-[8px]",style:{visibility:r&&t&&n?"visible":"hidden"},children:[v.jsx(LA,{value:l}),v.jsxs("div",{className:"w-[45px] flex justify-center font-nums",children:[l,"%"]})]})},kee=()=>{const[e,t]=bt(n=>[n.file,n.updateSettings]);return f.useEffect(()=>{(async()=>{const r=await zj();t({model:r})})()},[]),v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex gap-3 absolute top-[68px] left-[24px] items-center",children:[v.jsx(gJ,{}),v.jsx(Zq,{})]}),v.jsx(Vq,{}),v.jsx($ee,{}),v.jsx($J,{}),e?v.jsx(Xq,{file:e}):v.jsx(v.Fragment,{})]})},Ree=()=>{const[e,t]=f.useState(window.innerWidth),n=f.useCallback(()=>{t(window.innerWidth)},[]);if(f.useEffect(()=>(window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)})),e<768)return"mobile";if(e>=768&&e<1224)return"tablet";if(e>=1224)return"desktop"};function Tee(e){const{onSelection:t}=e,[n]=f.useState(`file-upload-${Math.random().toString()}`),r=Ree();function o(i){if(!(!i||!i.type.match("image.*")))try{if(i.size>20*1024*1024)throw new Error("file too large");t(i)}catch(l){alert(`error: ${l.message}`)}}return v.jsx("div",{className:"absolute flex w-screen h-screen justify-center items-center pointer-events-none",children:v.jsx("label",{htmlFor:n,className:"grid bg-background border-[2px] border-[dashed] rounded-lg min-w-[600px] hover:bg-primary hover:text-primary-foreground pointer-events-auto",children:v.jsxs("div",{className:"grid p-16 w-full h-full",onDragOver:i=>{i.stopPropagation(),i.preventDefault()},children:[v.jsx("input",{className:"hidden",id:n,name:n,type:"file",onChange:i=>{var l;const s=(l=i.currentTarget.files)==null?void 0:l[0];s&&o(s)},accept:"image/png, image/jpeg"}),v.jsx("p",{className:"text-center",children:r==="desktop"?"Click here or drag an image file":"Tap here to load your picture"})]})})})}const FA="ToastProvider",[cb,Pee,Aee]=zd("Toast"),[jA,Rte]=An("Toast",[Aee]),[Oee,gg]=jA(FA),zA=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:i=50,children:s}=e,[l,u]=f.useState(null),[d,h]=f.useState(0),m=f.useRef(!1),g=f.useRef(!1);return f.createElement(cb.Provider,{scope:t},f.createElement(Oee,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:i,toastCount:d,viewport:l,onViewportChange:u,onToastAdd:f.useCallback(()=>h(y=>y+1),[]),onToastRemove:f.useCallback(()=>h(y=>y-1),[]),isFocusedToastEscapeKeyDownRef:m,isClosePausedRef:g},s))};zA.propTypes={label(e){if(e.label&&typeof e.label=="string"&&!e.label.trim()){const t=`Invalid prop \`label\` supplied to \`${FA}\`. Expected non-empty \`string\`.`;return new Error(t)}return null}};const Mee="ToastViewport",Nee=["F8"],Q1="toast.viewportPause",J1="toast.viewportResume",Dee=f.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=Nee,label:o="Notifications ({hotkey})",...i}=e,s=gg(Mee,n),l=Pee(n),u=f.useRef(null),d=f.useRef(null),h=f.useRef(null),m=f.useRef(null),g=Be(t,m,s.onViewportChange),y=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=s.toastCount>0;f.useEffect(()=>{const C=S=>{var b;r.every(k=>S[k]||S.code===k)&&((b=m.current)===null||b===void 0||b.focus())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[r]),f.useEffect(()=>{const C=u.current,S=m.current;if(x&&C&&S){const b=()=>{if(!s.isClosePausedRef.current){const M=new CustomEvent(Q1);S.dispatchEvent(M),s.isClosePausedRef.current=!0}},E=()=>{if(s.isClosePausedRef.current){const M=new CustomEvent(J1);S.dispatchEvent(M),s.isClosePausedRef.current=!1}},k=M=>{!C.contains(M.relatedTarget)&&E()},P=()=>{C.contains(document.activeElement)||E()};return C.addEventListener("focusin",b),C.addEventListener("focusout",k),C.addEventListener("pointermove",b),C.addEventListener("pointerleave",P),window.addEventListener("blur",b),window.addEventListener("focus",E),()=>{C.removeEventListener("focusin",b),C.removeEventListener("focusout",k),C.removeEventListener("pointermove",b),C.removeEventListener("pointerleave",P),window.removeEventListener("blur",b),window.removeEventListener("focus",E)}}},[x,s.isClosePausedRef]);const _=f.useCallback(({tabbingDirection:C})=>{const b=l().map(E=>{const k=E.ref.current,P=[k,...qee(k)];return C==="forwards"?P:P.reverse()});return(C==="forwards"?b.reverse():b).flat()},[l]);return f.useEffect(()=>{const C=m.current;if(C){const S=b=>{const E=b.altKey||b.ctrlKey||b.metaKey;if(b.key==="Tab"&&!E){const O=document.activeElement,F=b.shiftKey;if(b.target===C&&F){var P;(P=d.current)===null||P===void 0||P.focus();return}const G=_({tabbingDirection:F?"backwards":"forwards"}),ae=G.findIndex(U=>U===O);if(j0(G.slice(ae+1)))b.preventDefault();else{var M,A;F?(M=d.current)===null||M===void 0||M.focus():(A=h.current)===null||A===void 0||A.focus()}}};return C.addEventListener("keydown",S),()=>C.removeEventListener("keydown",S)}},[l,_]),f.createElement(SB,{ref:u,role:"region","aria-label":o.replace("{hotkey}",y),tabIndex:-1,style:{pointerEvents:x?void 0:"none"}},x&&f.createElement(o$,{ref:d,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"forwards"});j0(C)}}),f.createElement(cb.Slot,{scope:n},f.createElement(Pe.ol,Y({tabIndex:-1},i,{ref:g}))),x&&f.createElement(o$,{ref:h,onFocusFromOutsideViewport:()=>{const C=_({tabbingDirection:"backwards"});j0(C)}}))}),Iee="ToastFocusProxy",o$=f.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,i=gg(Iee,n);return f.createElement(Um,Y({"aria-hidden":!0,tabIndex:0},o,{ref:t,style:{position:"fixed"},onFocus:s=>{var l;const u=s.relatedTarget;!((l=i.viewport)!==null&&l!==void 0&&l.contains(u))&&r()}}))}),vg="Toast",Lee="toast.swipeStart",Fee="toast.swipeMove",jee="toast.swipeCancel",zee="toast.swipeEnd",Bee=f.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:i,...s}=e,[l=!0,u]=Zr({prop:r,defaultProp:o,onChange:i});return f.createElement(bn,{present:n||l},f.createElement(BA,Y({open:l},s,{ref:t,onClose:()=>u(!1),onPause:Ft(e.onPause),onResume:Ft(e.onResume),onSwipeStart:ue(e.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ue(e.onSwipeMove,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ue(e.onSwipeCancel,d=>{d.currentTarget.setAttribute("data-swipe","cancel"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ue(e.onSwipeEnd,d=>{const{x:h,y:m}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),u(!1)})})))}),[Uee,Vee]=jA(vg,{onClose(){}}),BA=f.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:i,onClose:s,onEscapeKeyDown:l,onPause:u,onResume:d,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:g,onSwipeEnd:y,...x}=e,_=gg(vg,n),[C,S]=f.useState(null),b=Be(t,U=>S(U)),E=f.useRef(null),k=f.useRef(null),P=o||_.duration,M=f.useRef(0),A=f.useRef(P),O=f.useRef(0),{onToastAdd:F,onToastRemove:V}=_,J=Ft(()=>{var U;(C==null?void 0:C.contains(document.activeElement))&&((U=_.viewport)===null||U===void 0||U.focus()),s()}),G=f.useCallback(U=>{!U||U===1/0||(window.clearTimeout(O.current),M.current=new Date().getTime(),O.current=window.setTimeout(J,U))},[J]);f.useEffect(()=>{const U=_.viewport;if(U){const te=()=>{G(A.current),d==null||d()},L=()=>{const ie=new Date().getTime()-M.current;A.current=A.current-ie,window.clearTimeout(O.current),u==null||u()};return U.addEventListener(Q1,L),U.addEventListener(J1,te),()=>{U.removeEventListener(Q1,L),U.removeEventListener(J1,te)}}},[_.viewport,P,u,d,G]),f.useEffect(()=>{i&&!_.isClosePausedRef.current&&G(P)},[i,P,_.isClosePausedRef,G]),f.useEffect(()=>(F(),()=>V()),[F,V]);const ae=f.useMemo(()=>C?HA(C):null,[C]);return _.viewport?f.createElement(f.Fragment,null,ae&&f.createElement(Wee,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0},ae),f.createElement(Uee,{scope:n,onClose:J},Os.createPortal(f.createElement(cb.ItemSlot,{scope:n},f.createElement(_B,{asChild:!0,onEscapeKeyDown:ue(l,()=>{_.isFocusedToastEscapeKeyDownRef.current||J(),_.isFocusedToastEscapeKeyDownRef.current=!1})},f.createElement(Pe.li,Y({role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection},x,{ref:b,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:ue(e.onKeyDown,U=>{U.key==="Escape"&&(l==null||l(U.nativeEvent),U.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,J()))}),onPointerDown:ue(e.onPointerDown,U=>{U.button===0&&(E.current={x:U.clientX,y:U.clientY})}),onPointerMove:ue(e.onPointerMove,U=>{if(!E.current)return;const te=U.clientX-E.current.x,L=U.clientY-E.current.y,ie=!!k.current,K=["left","right"].includes(_.swipeDirection),Q=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,W=K?Q(0,te):0,le=K?0:Q(0,L),ge=U.pointerType==="touch"?10:2,Ve={x:W,y:le},Ue={originalEvent:U,delta:Ve};ie?(k.current=Ve,_p(Fee,m,Ue,{discrete:!1})):i$(Ve,_.swipeDirection,ge)?(k.current=Ve,_p(Lee,h,Ue,{discrete:!1}),U.target.setPointerCapture(U.pointerId)):(Math.abs(te)>ge||Math.abs(L)>ge)&&(E.current=null)}),onPointerUp:ue(e.onPointerUp,U=>{const te=k.current,L=U.target;if(L.hasPointerCapture(U.pointerId)&&L.releasePointerCapture(U.pointerId),k.current=null,E.current=null,te){const ie=U.currentTarget,K={originalEvent:U,delta:te};i$(te,_.swipeDirection,_.swipeThreshold)?_p(zee,y,K,{discrete:!0}):_p(jee,g,K,{discrete:!0}),ie.addEventListener("click",Q=>Q.preventDefault(),{once:!0})}})})))),_.viewport))):null});BA.propTypes={type(e){if(e.type&&!["foreground","background"].includes(e.type)){const t=`Invalid prop \`type\` supplied to \`${vg}\`. Expected \`foreground | background\`.`;return new Error(t)}return null}};const Wee=e=>{const{__scopeToast:t,children:n,...r}=e,o=gg(vg,t),[i,s]=f.useState(!1),[l,u]=f.useState(!1);return Xee(()=>s(!0)),f.useEffect(()=>{const d=window.setTimeout(()=>u(!0),1e3);return()=>window.clearTimeout(d)},[]),l?null:f.createElement(Md,{asChild:!0},f.createElement(Um,r,i&&f.createElement(f.Fragment,null,o.label," ",n)))},Hee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Kee=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return f.createElement(Pe.div,Y({},r,{ref:t}))}),Yee="ToastAction",UA=f.forwardRef((e,t)=>{const{altText:n,...r}=e;return n?f.createElement(WA,{altText:n,asChild:!0},f.createElement(VA,Y({},r,{ref:t}))):null});UA.propTypes={altText(e){return e.altText?null:new Error(`Missing prop \`altText\` expected on \`${Yee}\``)}};const Gee="ToastClose",VA=f.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=Vee(Gee,n);return f.createElement(WA,{asChild:!0},f.createElement(Pe.button,Y({type:"button"},r,{ref:t,onClick:ue(e.onClick,o.onClose)})))}),WA=f.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return f.createElement(Pe.div,Y({"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0},o,{ref:t}))});function HA(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),Zee(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!o)if(i){const s=r.dataset.radixToastAnnounceAlt;s&&t.push(s)}else t.push(...HA(r))}}),t}function _p(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,i=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?cx(o,i):o.dispatchEvent(i)}const i$=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),i=r>o;return t==="left"||t==="right"?i&&r>n:!i&&o>n};function Xee(e=()=>{}){const t=Ft(e);Pn(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function Zee(e){return e.nodeType===e.ELEMENT_NODE}function qee(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const 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();)t.push(n.currentNode);return t}function j0(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}const Qee=zA,KA=Dee,YA=Bee,GA=Hee,XA=Kee,ZA=UA,qA=VA,Jee=Qee,QA=f.forwardRef(({className:e,...t},n)=>v.jsx(KA,{ref:n,className:Ce("fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",e),tabIndex:-1,...t}));QA.displayName=KA.displayName;const ete=Om("group pointer-events-auto relative flex w-full items-center justify-between space-x-2 overflow-hidden rounded-md border p-4 pr-6 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),JA=f.forwardRef(({className:e,variant:t,...n},r)=>v.jsx(YA,{ref:r,className:Ce(ete({variant:t}),e),tabIndex:-1,...n}));JA.displayName=YA.displayName;const tte=f.forwardRef(({className:e,...t},n)=>v.jsx(ZA,{ref:n,className:Ce("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium transition-colors hover:bg-secondary focus:outline-none focus:ring-1 focus:ring-ring disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),tabIndex:-1,...t}));tte.displayName=ZA.displayName;const eO=f.forwardRef(({className:e,...t},n)=>v.jsx(qA,{ref:n,className:Ce("absolute right-1 top-1 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-1 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",tabIndex:-1,...t,children:v.jsx(yT,{className:"h-4 w-4"})}));eO.displayName=qA.displayName;const tO=f.forwardRef(({className:e,...t},n)=>v.jsx(GA,{ref:n,className:Ce("text-sm font-semibold [&+div]:text-xs",e),tabIndex:-1,...t}));tO.displayName=GA.displayName;const nO=f.forwardRef(({className:e,...t},n)=>v.jsx(XA,{ref:n,className:Ce("text-sm opacity-90",e),...t,tabIndex:-1}));nO.displayName=XA.displayName;function nte(){const{toasts:e}=Td();return v.jsxs(Jee,{children:[e.map(function({id:t,title:n,description:r,action:o,...i}){return v.jsxs(JA,{...i,children:[v.jsxs("div",{className:"grid gap-1",children:[n&&v.jsx(tO,{children:n}),r&&v.jsx(nO,{children:r})]}),o,v.jsx(eO,{})]},t)}),v.jsx(QA,{})]})}const rte=["image/jpeg","image/png","image/webp","image/bmp","image/tiff"];function ote(){const[e,t,n,r]=bt(g=>[g.file,g.updateAppState,g.setServerConfig,g.setFile]),o=Yj(),i=gH();f.useEffect(()=>{o&&r(o)},[o,r]),f.useEffect(()=>{t({windowSize:i})},[i]),f.useEffect(()=>{(async()=>{const y=await Fj();n(y),y.isDesktop&&dF()})()},[]);const s=f.useRef(0),l=f.useCallback(g=>{g.preventDefault(),g.stopPropagation()},[]),u=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current+=1},[]),d=f.useCallback(g=>{g.preventDefault(),g.stopPropagation(),s.current-=1,s.current>0},[]),h=f.useCallback(g=>{if(g.preventDefault(),g.stopPropagation(),g.dataTransfer.files&&g.dataTransfer.files.length>0){if(!(g.dataTransfer.files.length>1)){const y=g.dataTransfer.files[0],x=y.type;rte.includes(x)&&r(y)}g.dataTransfer.clearData()}},[]),m=f.useCallback(g=>{if(!g.clipboardData)return;const y=g.clipboardData.items,x=[].slice.call(y).filter(S=>S.type.indexOf("image")!==-1);if(x.length===0)return;g.preventDefault(),g.stopPropagation();const C=x[0].getAsFile();C&&r(C)},[]);return f.useEffect(()=>(window.addEventListener("dragenter",u),window.addEventListener("dragleave",d),window.addEventListener("dragover",l),window.addEventListener("drop",h),window.addEventListener("paste",m),function(){window.removeEventListener("dragenter",u),window.removeEventListener("dragleave",d),window.removeEventListener("dragover",l),window.removeEventListener("drop",h),window.removeEventListener("paste",m)})),v.jsxs("main",{className:"flex min-h-screen flex-col items-center justify-between w-full bg-[radial-gradient(circle_at_1px_1px,_#8e8e8e8e_1px,_transparent_0)] [background-size:20px_20px] bg-repeat",children:[v.jsx(nte,{}),v.jsx(tZ,{}),v.jsx(kee,{}),e?v.jsx(v.Fragment,{}):v.jsx(Tee,{onSelection:async g=>{r(g)}})]})}const sm=["light","dark"],ub="(prefers-color-scheme: dark)",ite=typeof window>"u",rO=f.createContext(void 0),ste=e=>f.useContext(rO)?Fe.createElement(f.Fragment,null,e.children):Fe.createElement(lte,e),ate=["light","dark"],lte=({forcedTheme:e,disableTransitionOnChange:t=!1,enableSystem:n=!0,enableColorScheme:r=!0,storageKey:o="theme",themes:i=ate,defaultTheme:s=n?"system":"light",attribute:l="data-theme",value:u,children:d,nonce:h})=>{const[m,g]=f.useState(()=>s$(o,s)),[y,x]=f.useState(()=>s$(o)),_=u?Object.values(u):i,C=f.useCallback(k=>{let P=k;if(!P)return;k==="system"&&n&&(P=a$());const M=u?u[P]:P,A=t?ute():null,O=document.documentElement;if(l==="class"?(O.classList.remove(..._),M&&O.classList.add(M)):M?O.setAttribute(l,M):O.removeAttribute(l),r){const F=sm.includes(s)?s:null,V=sm.includes(P)?P:F;O.style.colorScheme=V}A==null||A()},[]),S=f.useCallback(k=>{g(k);try{localStorage.setItem(o,k)}catch{}},[e]),b=f.useCallback(k=>{const P=a$(k);x(P),m==="system"&&n&&!e&&C("system")},[m,e]);f.useEffect(()=>{const k=window.matchMedia(ub);return k.addListener(b),b(k),()=>k.removeListener(b)},[b]),f.useEffect(()=>{const k=P=>{P.key===o&&S(P.newValue||s)};return window.addEventListener("storage",k),()=>window.removeEventListener("storage",k)},[S]),f.useEffect(()=>{C(e??m)},[e,m]);const E=f.useMemo(()=>({theme:m,setTheme:S,forcedTheme:e,resolvedTheme:m==="system"?y:m,themes:n?[...i,"system"]:i,systemTheme:n?y:void 0}),[m,S,e,y,n,i]);return Fe.createElement(rO.Provider,{value:E},Fe.createElement(cte,{forcedTheme:e,disableTransitionOnChange:t,enableSystem:n,enableColorScheme:r,storageKey:o,themes:i,defaultTheme:s,attribute:l,value:u,children:d,attrs:_,nonce:h}),d)},cte=f.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:i,value:s,attrs:l,nonce:u})=>{const d=i==="system",h=n==="class"?`var d=document.documentElement,c=d.classList;c.remove(${l.map(x=>`'${x}'`).join(",")});`:`var d=document.documentElement,n='${n}',s='setAttribute';`,m=o?sm.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",g=(x,_=!1,C=!0)=>{const S=s?s[x]:x,b=_?x+"|| ''":`'${S}'`;let E="";return o&&C&&!_&&sm.includes(x)&&(E+=`d.style.colorScheme = '${x}';`),n==="class"?E+=_||S?`c.add(${b})`:"null":S&&(E+=`d[s](n,${b})`),E},y=e?`!function(){${h}${g(e)}}()`:r?`!function(){try{${h}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${ub}',m=window.matchMedia(t);if(m.media!==t||m.matches){${g("dark")}}else{${g("light")}}}else if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}${d?"":"else{"+g(i,!1,!1)+"}"}${m}}catch(e){}}()`:`!function(){try{${h}var e=localStorage.getItem('${t}');if(e){${s?`var x=${JSON.stringify(s)};`:""}${g(s?"x[e]":"e",!0)}}else{${g(i,!1,!1)};}${m}}catch(t){}}();`;return Fe.createElement("script",{nonce:u,dangerouslySetInnerHTML:{__html:y}})},()=>!0),s$=(e,t)=>{if(ite)return;let n;try{n=localStorage.getItem(e)||void 0}catch{}return n||t},ute=()=>{const e=document.createElement("style");return e.appendChild(document.createTextNode("*{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}")),document.head.appendChild(e),()=>{window.getComputedStyle(document.body),setTimeout(()=>{document.head.removeChild(e)},1)}},a$=e=>(e||(e=window.matchMedia(ub)),e.matches?"dark":"light"),dte=new dL;z0.createRoot(document.getElementById("root")).render(v.jsx(Fe.StrictMode,{children:v.jsx(gL,{client:dte,children:v.jsx(ste,{defaultTheme:"dark",disableTransitionOnChange:!0,children:v.jsx(UU,{children:v.jsx(ote,{})})})})})); diff --git a/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png b/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png new file mode 100644 index 0000000..0baa366 Binary files /dev/null and b/py/iopaint/web_app/assets/kofi_button_black-XI_Dr2zg.png differ diff --git a/py/iopaint/web_app/index.html b/py/iopaint/web_app/index.html new file mode 100644 index 0000000..954c49b --- /dev/null +++ b/py/iopaint/web_app/index.html @@ -0,0 +1,13 @@ + + + + + + IOPaint + + + + +
+ + diff --git a/py/iopaint/web_config.py b/py/iopaint/web_config.py new file mode 100644 index 0000000..534a0ca --- /dev/null +++ b/py/iopaint/web_config.py @@ -0,0 +1,307 @@ +import json +import os +from pathlib import Path + +from .schema import ( + Device, + InteractiveSegModel, + RemoveBGModel, + RealESRGANModel, + ApiConfig, +) + +os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" + +from datetime import datetime +from json import JSONDecodeError + +import gradio as gr +from .download import scan_models +from loguru import logger + +from .const import * + + +_config_file: Path = None + + +default_configs = dict( + host="127.0.0.1", + port=8080, + inbrowser=True, + model=DEFAULT_MODEL, + model_dir=DEFAULT_MODEL_DIR, + no_half=False, + low_mem=False, + cpu_offload=False, + disable_nsfw_checker=False, + local_files_only=False, + cpu_textencoder=False, + device=Device.cuda, + input=None, + output_dir=None, + quality=95, + enable_interactive_seg=False, + interactive_seg_model=InteractiveSegModel.vit_b, + interactive_seg_device=Device.cpu, + enable_remove_bg=False, + remove_bg_model=RemoveBGModel.briaai_rmbg_1_4, + enable_anime_seg=False, + enable_realesrgan=False, + realesrgan_device=Device.cpu, + realesrgan_model=RealESRGANModel.realesr_general_x4v3, + enable_gfpgan=False, + gfpgan_device=Device.cpu, + enable_restoreformer=False, + restoreformer_device=Device.cpu, +) + + +class WebConfig(ApiConfig): + model_dir: str = DEFAULT_MODEL_DIR + + +def load_config(p: Path) -> WebConfig: + if p.exists(): + with open(p, "r", encoding="utf-8") as f: + try: + return WebConfig(**{**default_configs, **json.load(f)}) + except JSONDecodeError: + print(f"Load config file failed, using default configs") + return WebConfig(**default_configs) + else: + return WebConfig(**default_configs) + + +def save_config( + host, + port, + model, + model_dir, + no_half, + low_mem, + cpu_offload, + disable_nsfw_checker, + local_files_only, + cpu_textencoder, + device, + input, + output_dir, + quality, + enable_interactive_seg, + interactive_seg_model, + interactive_seg_device, + enable_remove_bg, + remove_bg_model, + enable_anime_seg, + enable_realesrgan, + realesrgan_device, + realesrgan_model, + enable_gfpgan, + gfpgan_device, + enable_restoreformer, + restoreformer_device, + inbrowser, +): + config = WebConfig(**locals()) + if str(config.input) == ".": + config.input = None + if str(config.output_dir) == ".": + config.output_dir = None + config.model = config.model.strip() + print(config.model_dump_json(indent=4)) + if config.input and not os.path.exists(config.input): + return "[Error] Input file or directory does not exist" + + current_time = datetime.now().strftime("%H:%M:%S") + msg = f"[{current_time}] Successful save config to: {str(_config_file.absolute())}" + logger.info(msg) + try: + with open(_config_file, "w", encoding="utf-8") as f: + f.write(config.model_dump_json(indent=4)) + except Exception as e: + return f"Save configure file failed: {str(e)}" + return msg + + +def change_current_model(new_model): + return new_model + + +def main(config_file: Path): + global _config_file + _config_file = config_file + + init_config = load_config(config_file) + downloaded_models = [it.name for it in scan_models()] + + with gr.Blocks() as demo: + with gr.Row(): + with gr.Column(): + gr.Textbox(config_file, label="Config file", interactive=False) + with gr.Column(): + save_btn = gr.Button(value="Save configurations") + message = gr.HTML() + + with gr.Tabs(): + with gr.Tab("Common"): + with gr.Row(): + host = gr.Textbox(init_config.host, label="Host") + port = gr.Number(init_config.port, label="Port", precision=0) + inbrowser = gr.Checkbox(init_config.inbrowser, label=INBROWSER_HELP) + + with gr.Column(): + model = gr.Textbox( + init_config.model, + label="Current Model. This is the model that will be used when the service starts. " + "If the model has not been downloaded before, it will be automatically downloaded. " + "You can select a model from the dropdown box below or manually enter the SD/SDXL model ID from HuggingFace, for example, runwayml/stable-diffusion-inpainting.", + ) + with gr.Row(): + recommend_model = gr.Dropdown( + ["lama", "mat", "migan"] + DIFFUSION_MODELS, + label="Recommended Models", + ) + downloaded_model = gr.Dropdown( + downloaded_models, label="Downloaded Models" + ) + + device = gr.Radio( + Device.values(), label="Device", value=init_config.device + ) + quality = gr.Slider( + value=95, + label=f"Image Quality ({QUALITY_HELP})", + minimum=75, + maximum=100, + step=1, + ) + + no_half = gr.Checkbox(init_config.no_half, label=f"{NO_HALF_HELP}") + cpu_offload = gr.Checkbox( + init_config.cpu_offload, label=f"{CPU_OFFLOAD_HELP}" + ) + low_mem = gr.Checkbox(init_config.low_mem, label=f"{LOW_MEM_HELP}") + cpu_textencoder = gr.Checkbox( + init_config.cpu_textencoder, label=f"{CPU_TEXTENCODER_HELP}" + ) + disable_nsfw_checker = gr.Checkbox( + init_config.disable_nsfw_checker, label=f"{DISABLE_NSFW_HELP}" + ) + local_files_only = gr.Checkbox( + init_config.local_files_only, label=f"{LOCAL_FILES_ONLY_HELP}" + ) + + with gr.Column(): + model_dir = gr.Textbox( + init_config.model_dir, label=f"{MODEL_DIR_HELP}" + ) + input = gr.Textbox( + init_config.input, + label=f"Input file or directory. {INPUT_HELP}", + ) + output_dir = gr.Textbox( + init_config.output_dir, + label=f"Output directory. {OUTPUT_DIR_HELP}", + ) + + with gr.Tab("Plugins"): + with gr.Row(): + enable_interactive_seg = gr.Checkbox( + init_config.enable_interactive_seg, label=INTERACTIVE_SEG_HELP + ) + interactive_seg_model = gr.Radio( + InteractiveSegModel.values(), + label=f"Segment Anything models. {INTERACTIVE_SEG_MODEL_HELP}", + value=init_config.interactive_seg_model, + ) + interactive_seg_device = gr.Radio( + Device.values(), + label="Segment Anything Device", + value=init_config.interactive_seg_device, + ) + with gr.Row(): + enable_remove_bg = gr.Checkbox( + init_config.enable_remove_bg, label=REMOVE_BG_HELP + ) + remove_bg_model = gr.Radio( + RemoveBGModel.values(), + label="Remove bg model", + value=init_config.remove_bg_model, + ) + with gr.Row(): + enable_anime_seg = gr.Checkbox( + init_config.enable_anime_seg, label=ANIMESEG_HELP + ) + + with gr.Row(): + enable_realesrgan = gr.Checkbox( + init_config.enable_realesrgan, label=REALESRGAN_HELP + ) + realesrgan_device = gr.Radio( + Device.values(), + label="RealESRGAN Device", + value=init_config.realesrgan_device, + ) + realesrgan_model = gr.Radio( + RealESRGANModel.values(), + label="RealESRGAN model", + value=init_config.realesrgan_model, + ) + with gr.Row(): + enable_gfpgan = gr.Checkbox( + init_config.enable_gfpgan, label=GFPGAN_HELP + ) + gfpgan_device = gr.Radio( + Device.values(), + label="GFPGAN Device", + value=init_config.gfpgan_device, + ) + with gr.Row(): + enable_restoreformer = gr.Checkbox( + init_config.enable_restoreformer, label=RESTOREFORMER_HELP + ) + restoreformer_device = gr.Radio( + Device.values(), + label="RestoreFormer Device", + value=init_config.restoreformer_device, + ) + + downloaded_model.change(change_current_model, [downloaded_model], model) + recommend_model.change(change_current_model, [recommend_model], model) + + save_btn.click( + save_config, + [ + host, + port, + model, + model_dir, + no_half, + low_mem, + cpu_offload, + disable_nsfw_checker, + local_files_only, + cpu_textencoder, + device, + input, + output_dir, + quality, + enable_interactive_seg, + interactive_seg_model, + interactive_seg_device, + enable_remove_bg, + remove_bg_model, + enable_anime_seg, + enable_realesrgan, + realesrgan_device, + realesrgan_model, + enable_gfpgan, + gfpgan_device, + enable_restoreformer, + restoreformer_device, + inbrowser, + ], + message, + ) + demo.launch(inbrowser=True, show_api=False) diff --git a/py/lama.py b/py/lama.py new file mode 100644 index 0000000..ed95e45 --- /dev/null +++ b/py/lama.py @@ -0,0 +1,111 @@ +import os.path +import shutil +from pathlib import Path + +from .imagefunc import * +from iopaint import cli + +NODE_NAME = 'LaMa' + +class LaMa: + + def __init__(self): + pass + + @classmethod + def INPUT_TYPES(self): + model_list = ['lama', 'ldm', 'zits', 'mat', 'fcf', 'manga', 'opencv'] + device_list = ['cuda', 'cpu'] + return { + "required": { + "image": ("IMAGE", ), # + "mask": ("MASK",), # + "lama_model": (model_list,), + "device": (device_list,), + "invert_mask": ("BOOLEAN", {"default": False}), # 反转mask + "mask_grow": ("INT", {"default": 25, "min": -255, "max": 255, "step": 1}), + "mask_blur": ("INT", {"default": 8, "min": -255, "max": 255, "step": 1}), + }, + "optional": { + } + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("image",) + FUNCTION = 'lama' + CATEGORY = '😺dzNodes/LayerUtility' + OUTPUT_NODE = True + + def lama(self, image, mask, lama_model, device, invert_mask, mask_grow, mask_blur): + + l_images = [] + l_masks = [] + ret_images = [] + + for l in image: + l_images.append(torch.unsqueeze(l, 0)) + m = tensor2pil(l) + if m.mode == 'RGBA': + l_masks.append(m.split()[-1]) + if mask is not None: + if mask.dim() == 2: + layer_mask = torch.unsqueeze(mask, 0) + l_masks = [] + for m in mask: + if invert_mask: + m = 1 - m + l_masks.append(tensor2pil(torch.unsqueeze(m, 0)).convert('L')) + if len(l_masks) == 0: + log(f"Error: {NODE_NAME} skipped, because the available mask is not found.", message_type='error') + return (image,) + + max_batch = max(len(l_images), len(l_masks)) + + for i in range(max_batch): + _image = l_images[i] if i < len(l_images) else l_images[-1] + _mask = l_masks[i] if i < len(l_masks) else l_masks[-1] + if mask_grow or mask_blur: + _mask = tensor2pil(expand_mask(image2mask(_mask), mask_grow, mask_blur)) + + if lama_model == 'opencv': + ret_image = pixel_spread(tensor2pil(_image).convert('RGB'), ImageChops.invert(_mask.convert('RGB'))) + else: + temp_dir = os.path.join(folder_paths.get_temp_directory(), generate_random_name('_lama_', '_temp', 16)) + if os.path.isdir(temp_dir): + shutil.rmtree(temp_dir) + image_dir = os.path.join(temp_dir, 'image') + mask_dir = os.path.join(temp_dir, 'mask') + result_dir = os.path.join(temp_dir, 'result') + try: + os.makedirs(image_dir) + os.makedirs(mask_dir) + os.makedirs(result_dir) + except Exception as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary folder.", message_type='error') + return (image, ) + file_name = os.path.join(generate_random_name('lama_', '_temp', 16) + '.png') + try: + tensor2pil(_image).save(os.path.join(image_dir, file_name)) + _mask.save(os.path.join(mask_dir, file_name)) + except IOError as e: + print(e) + log(f"Error: {NODE_NAME} skipped, because unable to create temporary file.", message_type='error') + return (image, ) + # process + cli.run(model=lama_model, device=device, image=Path(image_dir), mask=Path(mask_dir), output=Path(result_dir)) + ret_image = check_image_file(os.path.join(result_dir, file_name), 500) + shutil.rmtree(temp_dir) + ret_images.append(pil2tensor(ret_image)) + + + log(f"{NODE_NAME} Processed {len(ret_images)} image(s).", message_type='finish') + return (torch.cat(ret_images, dim=0),) + +NODE_CLASS_MAPPINGS = { + "LayerUtility: LaMa": LaMa +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LayerUtility: LaMa": "LayerUtility: LaMa" +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index ff5819e..61c8ea6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -12,4 +12,4 @@ addict yapf colour-science wget -mediapipe \ No newline at end of file +mediapipe diff --git a/workflow/lama_example.json b/workflow/lama_example.json new file mode 100644 index 0000000..c480b00 --- /dev/null +++ b/workflow/lama_example.json @@ -0,0 +1,788 @@ +{ + "last_node_id": 35, + "last_link_id": 71, + "nodes": [ + { + "id": 15, + "type": "PreviewImage", + "pos": [ + 1680, + 650 + ], + "size": { + "0": 295.9647216796875, + "1": 320.621337890625 + }, + "flags": {}, + "order": 11, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 23 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 29, + "type": "PreviewImage", + "pos": [ + 1680, + 1040 + ], + "size": { + "0": 295.9647216796875, + "1": 320.621337890625 + }, + "flags": {}, + "order": 12, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 62 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 8, + "type": "PreviewImage", + "pos": [ + 1680, + 230 + ], + "size": { + "0": 299.51416015625, + "1": 327.3353271484375 + }, + "flags": {}, + "order": 10, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 8 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 31, + "type": "PreviewImage", + "pos": [ + 2410, + 240 + ], + "size": { + "0": 299.51416015625, + "1": 327.3353271484375 + }, + "flags": {}, + "order": 13, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 65 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 33, + "type": "PreviewImage", + "pos": [ + 2410, + 630 + ], + "size": { + "0": 299.51416015625, + "1": 327.3353271484375 + }, + "flags": {}, + "order": 14, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 68 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 35, + "type": "PreviewImage", + "pos": [ + 2420, + 1020 + ], + "size": { + "0": 299.51416015625, + "1": 327.3353271484375 + }, + "flags": {}, + "order": 15, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 71 + } + ], + "properties": { + "Node name for S&R": "PreviewImage" + } + }, + { + "id": 25, + "type": "Reroute", + "pos": [ + 1132, + 727 + ], + "size": [ + 75, + 26 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [ + { + "name": "", + "type": "*", + "link": 54 + } + ], + "outputs": [ + { + "name": "", + "type": "MASK", + "links": [ + 58, + 59, + 61, + 64, + 67, + 70 + ], + "slot_index": 0 + } + ], + "properties": { + "showOutputText": false, + "horizontal": false + } + }, + { + "id": 27, + "type": "Reroute", + "pos": [ + 1129, + 439 + ], + "size": [ + 75, + 26 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [ + { + "name": "", + "type": "*", + "link": 55 + } + ], + "outputs": [ + { + "name": "", + "type": "IMAGE", + "links": [ + 56, + 57, + 60, + 63, + 66, + 69 + ], + "slot_index": 0 + } + ], + "properties": { + "showOutputText": false, + "horizontal": false + } + }, + { + "id": 24, + "type": "LayerMask: RemBgUltra", + "pos": [ + 785, + 772 + ], + "size": { + "0": 315, + "1": 150 + }, + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 36 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": null, + "shape": 3 + }, + { + "name": "mask", + "type": "MASK", + "links": [ + 54 + ], + "shape": 3, + "slot_index": 1 + } + ], + "properties": { + "Node name for S&R": "LayerMask: RemBgUltra" + }, + "widgets_values": [ + 8, + 0.01, + 0.99, + false + ] + }, + { + "id": 2, + "type": "LoadImage", + "pos": [ + 431, + 439 + ], + "size": { + "0": 323.62158203125, + "1": 420.20391845703125 + }, + "flags": {}, + "order": 0, + "mode": 0, + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 36, + 55 + ], + "shape": 3, + "slot_index": 0 + }, + { + "name": "MASK", + "type": "MASK", + "links": null, + "shape": 3 + } + ], + "properties": { + "Node name for S&R": "LoadImage" + }, + "widgets_values": [ + "512x512with_background (24).png", + "image" + ] + }, + { + "id": 7, + "type": "LayerUtility: LaMa", + "pos": [ + 1300, + 320 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 56 + }, + { + "name": "mask", + "type": "MASK", + "link": 58 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 8 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "lama", + "cuda", + false, + 25, + 6 + ] + }, + { + "id": 14, + "type": "LayerUtility: LaMa", + "pos": [ + 1300, + 710 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 57 + }, + { + "name": "mask", + "type": "MASK", + "link": 59 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 23 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "ldm", + "cuda", + false, + 25, + 6 + ] + }, + { + "id": 28, + "type": "LayerUtility: LaMa", + "pos": [ + 1290, + 1030 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 6, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 60 + }, + { + "name": "mask", + "type": "MASK", + "link": 61 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 62 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "zits", + "cuda", + false, + 25, + 6 + ] + }, + { + "id": 30, + "type": "LayerUtility: LaMa", + "pos": [ + 2036, + 314 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 7, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 63 + }, + { + "name": "mask", + "type": "MASK", + "link": 64 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 65 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "mat", + "cuda", + false, + 25, + 6 + ] + }, + { + "id": 32, + "type": "LayerUtility: LaMa", + "pos": [ + 2037, + 724 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 8, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 66 + }, + { + "name": "mask", + "type": "MASK", + "link": 67 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 68 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "fcf", + "cuda", + false, + 25, + 6 + ] + }, + { + "id": 34, + "type": "LayerUtility: LaMa", + "pos": [ + 2043, + 1042 + ], + "size": { + "0": 315, + "1": 174 + }, + "flags": {}, + "order": 9, + "mode": 0, + "inputs": [ + { + "name": "image", + "type": "IMAGE", + "link": 69 + }, + { + "name": "mask", + "type": "MASK", + "link": 70 + } + ], + "outputs": [ + { + "name": "image", + "type": "IMAGE", + "links": [ + 71 + ], + "shape": 3, + "slot_index": 0 + } + ], + "properties": { + "Node name for S&R": "LayerUtility: LaMa" + }, + "widgets_values": [ + "opencv", + "cuda", + false, + 25, + 6 + ] + } + ], + "links": [ + [ + 8, + 7, + 0, + 8, + 0, + "IMAGE" + ], + [ + 23, + 14, + 0, + 15, + 0, + "IMAGE" + ], + [ + 36, + 2, + 0, + 24, + 0, + "IMAGE" + ], + [ + 54, + 24, + 1, + 25, + 0, + "*" + ], + [ + 55, + 2, + 0, + 27, + 0, + "*" + ], + [ + 56, + 27, + 0, + 7, + 0, + "IMAGE" + ], + [ + 57, + 27, + 0, + 14, + 0, + "IMAGE" + ], + [ + 58, + 25, + 0, + 7, + 1, + "MASK" + ], + [ + 59, + 25, + 0, + 14, + 1, + "MASK" + ], + [ + 60, + 27, + 0, + 28, + 0, + "IMAGE" + ], + [ + 61, + 25, + 0, + 28, + 1, + "MASK" + ], + [ + 62, + 28, + 0, + 29, + 0, + "IMAGE" + ], + [ + 63, + 27, + 0, + 30, + 0, + "IMAGE" + ], + [ + 64, + 25, + 0, + 30, + 1, + "MASK" + ], + [ + 65, + 30, + 0, + 31, + 0, + "IMAGE" + ], + [ + 66, + 27, + 0, + 32, + 0, + "IMAGE" + ], + [ + 67, + 25, + 0, + 32, + 1, + "MASK" + ], + [ + 68, + 32, + 0, + 33, + 0, + "IMAGE" + ], + [ + 69, + 27, + 0, + 34, + 0, + "IMAGE" + ], + [ + 70, + 25, + 0, + 34, + 1, + "MASK" + ], + [ + 71, + 34, + 0, + 35, + 0, + "IMAGE" + ] + ], + "groups": [], + "config": {}, + "extra": {}, + "version": 0.4 +} \ No newline at end of file